简体   繁体   English

将 Pandas df 单元格转换为列名

[英]Convert pandas df cells to say column name

I have a df like this:我有一个这样的 df:

0   1   2   3   4   5   
abc 0   1   0   0   1
bcd 0   0   1   0   0   
def 0   0   0   1   0

How can I convert the dataframe cells to be the column name if there's a 1 in the cell?如果单元格中有 1,如何将数据框单元格转换为列名? Looks like this:看起来像这样:

0   1   2   3   4   5   
abc 0   2   0   0   5
bcd 0   0   3   0   0   
def 0   0   0   4   0

Let us try让我们试试

df.loc[:,'1':] = df.loc[:,'1':]  * df.columns[1:].astype(int)
df
Out[468]: 
     0  1  2  3  4  5
0  abc  0  2  0  0  5
1  bcd  0  0  3  0  0
2  def  0  0  0  4  0

I'd suggest you simply do the logic for each column, where the value is 1 in the given column, set the value as the column name我建议您简单地为每一列执行逻辑,其中给定列中的值为1 ,将该值设置为列名

for col in df.columns:
    df.loc[df[col] == 1, col] = col

We can use np.where over the whole dataframe:我们可以在整个数据帧上使用np.where

values = np.where(df.eq(1), df.columns, df)
df = pd.DataFrame(values, columns=df.columns)

     0  1  2  3  4  5
0  abc  0  2  0  0  5
1  bcd  0  0  3  0  0
2  def  0  0  0  4  0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM