gpt4 book ai didi

python - 如何显示数据框,其中列连续显示两次

转载 作者:行者123 更新时间:2023-12-03 20:02:29 26 4
gpt4 key购买 nike

例如:

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
编辑:对于一般数据总是 4 列的解决方案,计数 N按行长:
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

关于python - 如何显示数据框,其中列连续显示两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65104345/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com