[英]Pandas: transpose doesn't transpose rows to columns
我正在使用以下代码读取 csv:
df=pd.read_csv(file, index_col="Votes")
这给出了这个结果:
votes 10 20 5 30
1st a e b c
2nd b a c e
我想将其转置为如下所示:
votes 1st 2nd
10 a b
20 e a
5 b c
30 c e
我希望votes
1st
、 2nd
成为列。 但是像这样转置df_t = df.T
会将列保留为10
、 20
等。
如何让列被识别为votes
, 1st
等?
如果有帮助,我的近期目标是将每个a
in 1st
等的votes
相加(排名选择投票)。
从您的 DataFrame :
>>> import pandas as pd
>>> from io import StringIO
>>> df = pd.read_csv(StringIO("""
votes,10,20,5,30
1st,a,e,b,c
2nd,b,a,c,e
"""), sep=',', index_col="votes")
>>> df
10 20 5 30
votes
1st a e b c
2nd b a c e
我们确实可以使用T
来按预期转置它:
>>> df_T = df.T
>>> df_T
votes 1st 2nd
10 a b
20 e a
5 b c
30 c e
然后,如评论部分所述,我们可以像这样设置索引:
>>> df_T['votes'] = df_T.index
>>> df_T = df_T.reset_index(drop=True)
>>> df_T.columns.name = None
>>> df_T
1st 2nd votes
0 a b 10
1 e a 20
2 b c 5
3 c e 30
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.