Python 如何使用唯一名称透视表并避免空值?
我有一个Pandas数据框,当我在一个具有唯一值(混合数据类型)的列上旋转时,它如下所示Python 如何使用唯一名称透视表并避免空值?,python,pandas,Python,Pandas,我有一个Pandas数据框,当我在一个具有唯一值(混合数据类型)的列上旋转时,它如下所示 In [1]: import pandas as pd In [2]: import numpy as np In [3]: df = pd.DataFrame({'A' : ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'],'B' : [0.815, 0.765, 'two', 'four', 0.981, 'six', 's
In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: df = pd.DataFrame({'A' : ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'],'B' : [0.815, 0.765, 'two', 'four', 0.981, 'six', 'seven', 'eight']})
In [4]: df
Out[4]:
A B
0 one 0.815
1 two 0.765
2 three two
3 four four
4 five 0.981
5 six six
6 seven seven
7 eight eight
In [5]: df.pivot(columns='A', values='B')
Out[5]:
A eight five four one seven six three two
0 None None None 0.815 None None None None
1 None None None None None None None 0.765
2 None None None None None None two None
3 None None four None None None None None
4 None 0.981 None None None None None None
5 None None None None None six None None
6 None None None None seven None None None
7 eight None None None None None None None
有没有一种方法可以将列“a”上的此数据帧旋转到一行,而不使用“None”值?我认为您建议转置数据帧
df.set_index('A').T
之所以会出现这种情况,是因为脚本会在B列中查找值,如果没有找到值,则只会返回
None
。如您所见,(7,8)=8,这是B列的第8行,(4,5)=0.981,这是B列的第5行,以此类推。这里真正需要的是transpose()
如果要更改列标题,可以执行以下操作:
df_t.column = df_t.iloc[0] #replaces the column headers with the first row
df_t = df_t[1:] #deletes the first line so you don't see a duplicate
>>> df_t
A one two three four five six seven eight
B 0.815 0.765 two four 0.981 six seven eight
df_t.column = df_t.iloc[0] #replaces the column headers with the first row
df_t = df_t[1:] #deletes the first line so you don't see a duplicate
>>> df_t
A one two three four five six seven eight
B 0.815 0.765 two four 0.981 six seven eight