如何显示数据框,其中列连续显示两次
例如:
df_test=pd.DataFrame([('tokyo',123),('london',11),('sydney',22),('taiwan',33),('hongkong',23),('la', 32)], columns=['city','count'])
city count
0 tokyo 123
1 london 11
2 sydney 22
3 taiwan 33
4 hongkong 23
5 la 32
我希望它看起来像这样,因为行比列多,使其易于阅读。
city count city count
0 tokyo 123 taiwan 33
1 london 11 hongkong 23
2 sydney 22 la 32
回答
您可以使用模数和整数除以索引值并重塑为DataFrame.unstack,最后排序第二级并避免重复的列名称展平MultiIndex in columns:
df = (df_test.set_index([df_test.index % 2, df_test.index // 2])
.unstack()
.sort_index(axis=1, level=1, sort_remaining=False))
df.columns = df.columns.map(lambda x: f'{x[0]}{x[1]}')
print (df)
city0 count0 city1 count1
0 tokyo 123 sydney 22
1 london 11 taiwan 33
如果可能,不是默认值RangeIndex是可能的使用:
df_test=pd.DataFrame([('tokyo',123),('london',11),('sydney',22),('taiwan',33)],
columns=['city','count'],
index=list('abcd'))
print (df_test)
city count
a tokyo 123
b london 11
c sydney 22
d taiwan 33
arr = np.arange(len(df_test))
df = (df_test.set_index([arr % 2, arr // 2])
.unstack()
.sort_index(axis=1, level=1, sort_remaining=False))
df.columns = df.columns.map(lambda x: f'{x[0]}{x[1]}')
print (df)
city0 count0 city1 count1
0 tokyo 123 sydney 22
1 london 11 taiwan 33
编辑:对于N按行长计数的一般数据始终为 4 列的解决方案:
N = len(df_test) % 2 + len(df_test) // 2
arr = np.arange(len(df_test))
df = (df_test.set_index([arr % N, arr // N])
.unstack()
.sort_index(axis=1, level=1, sort_remaining=False))
df.columns = df.columns.map(lambda x: f'{x[0]}{x[1]}')
print (df)
city0 count0 city1 count1
0 tokyo 123 taiwan 33
1 london 11 hongkong 23
2 sydney 22 la 32
- fantastic. Thanks