如何显示数据框,列在一行中显示两次

2024-09-27 21:24:32 发布

您现在位置:Python中文网/ 问答频道 /正文

例如:

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


Tags: columnstestcitydataframedfcountlapd
1条回答
网友
1楼 · 发布于 2024-09-27 21:24:32

您可以按索引值使用模和整数除法,并按^{}重新整形,最后一次排序为第二级,为避免重复列名称,请将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

相关问题 更多 >

    热门问题