如何使用唯一名称透视表并避免使用空值?

时间:2016-12-21 02:43:14

标签: 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', '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”列上的数据框转换为没有“无”值的单行?

2 个答案:

答案 0 :(得分:3)

我认为您建议转置数据框。

df.set_index('A').T

答案 1 :(得分:0)

这种情况正在发生,因为脚本会在B列中查找值,并且只要找不到值,它就会返回None。如你所见,(7,8)= 8,这是B列的第8行,(4,5)= 0.981,这是B列的第5行,等等。你真正想要的是{{ 1}}。

transpose()

如果要更改列标题,可以执行以下操作:

import pandas as pd
>>> df
       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

>>> df_t = df.transpose()
>>> df_t
       0      1      2     3      4    5      6      7
A    one    two  three  four   five  six  seven  eight
B  0.815  0.765    two  four  0.981  six  seven  eight