熊猫,如果值等于1,则指定列名

时间:2020-08-06 08:54:29

标签: python pandas

我有一个数据框

   Blue  Red
0   0     0
1   1     0
2   0     1
3   0     0
4   0     0

我想说值是否等于1,然后给出列名。所以预期的输出是

   Blue  Red
0   0     0
1   Blue  0
2   0     Red
3   0     0
4   0     0

我几乎以一种非常复杂的方式做到了这一点,我希望有一种简单的方法吗?

2 个答案:

答案 0 :(得分:3)

DataFrame.maskcolumns转换为Series以避免使用AttributeError: 'Index' object has no attribute '_info_axis_number'(在某些较新的熊猫版本中):

df = df.mask(df.eq(1), df.columns.to_series(), axis=1)
print (df)
   Blue  Red
0     0    0
1  Blue    0
2     0  Red
3     0    0
4     0    0

替代numpy.where

df = pd.DataFrame(np.where(df.eq(1), df.columns, df), 
                  index=df.index, 
                  columns=df.columns)
print (df)
   Blue  Red
0     0    0
1  Blue    0
2     0  Red
3     0    0
4     0    0

答案 1 :(得分:1)

这是通过对列和行的迭代: 考虑数据帧是df1:

for name in df1.columns:
    for row in df1.index:
        if df1.loc[row,name] == 1:
            df1.loc[row,name] = name

print(df1)
   Blue  Red
0     0    0
1  Blue    0
2     0  Red
3     0    0
4     0    0