pandas dataframe - 根据列标题更改值

时间:2012-08-12 08:12:11

标签: python pandas

我有dataframe,如下所示:

In [74]: data2

Out[74]: 
            a  b  c

2012-06-12  0  1  1
2012-06-13  1  1  0
2012-06-14  1  0  1
2012-06-15  1  0  1
2012-06-16  1  1  0
2012-06-17  1  0  1

有没有办法让值=列标题值= 1?

结果df:

            a  b  c

2012-06-12  0  b  c
2012-06-13  a  b  0
2012-06-14  a  0  c
2012-06-15  a  0  c
2012-06-16  a  b  0
2012-06-17  a  0  c

然后删除= 0的值,使df减少到2列: (列标题此时不相关)

结果df:

            1  2  
2012-06-12  c  b  
2012-06-13  a  b  
2012-06-14  a  c  
2012-06-15  a  c  
2012-06-16  a  b  
2012-06-17  a  c  

2 个答案:

答案 0 :(得分:6)

你也可以召唤一些更深层次的熊猫 - 并做:

In [28]: df.apply(lambda x: x.astype(object).replace(1, x.name))
Out[28]: 
            a  b  c
2012-06-12  0  b  c
2012-06-13  a  b  0
2012-06-14  a  0  c
2012-06-15  a  0  c
2012-06-16  a  b  0
2012-06-17  a  0  c

答案 1 :(得分:5)

from pandas import *
df = DataFrame([[0, 1, 1], [1, 1, 0], [1, 0, 1],], columns=['a','b','c'])

foo = []
for i in df.index:
    foo.append( df.columns[df.ix[i] == 1])
DataFrame(foo, index = df.index)

返回:

   0  1
0  b  c
1  a  b
2  a  c