我想将dataframe的值替换为python中的列名.我应该怎么做? [英] I want to replace values of dataframe as a column name in python. How am I suppose to do that?

查看:491
本文介绍了我想将dataframe的值替换为python中的列名.我应该怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用循环转换以下值.

I want to convert following values using loop.

        {'Id':2, 'A':"no", 'B':"no", 'C':"no", 'D':"yes"},
        {'Id':3, 'A':"yes", 'B':"yes", 'C':"yes", 'D':"no"},
        {'Id':4, 'A':"yes", 'B':"no", 'C':"yes", 'D':"no"},
        {'Id':5, 'A':"no", 'B':"yes", 'C':"no", 'D':"yes"}]

https://ibb.co/7NL69BY (链接到数据框)

我已经使用'map'来显示单行.但我想循环播放.

I have used 'map' for indivisual rows. But I want to loop it.

df['B'] = df['B'].map({"yes": "B", "no": "-"})
df['C'] = df['C'].map({"yes": "C", "no": "-"})
df['D'] = df['D'].map({"yes": "D", "no": "-"})

(链接到结果) https://ibb.co/JsJjqZr 请帮助我使用循环.

(Link to result)https://ibb.co/JsJjqZr Help me to use loop please.

推荐答案

您可以使用以下解决方案:

You can use this solution:

import pandas as pd
x = pd.DataFrame([{'Id':2, 'A':"no", 'B':"no", 'C':"no", 'D':"yes"}, 
           {'Id':3, 'A':"yes", 'B':"yes", 'C':"yes", 'D':"no"}, 
           {'Id':4, 'A':"yes", 'B':"no", 'C':"yes", 'D':"no"}, 
           {'Id':5, 'A':"no", 'B':"yes", 'C':"no", 'D':"yes"}])  
x.set_index('Id')
headers = x.columns.to_list()
for col in headers:
    x[col] = x[col].map({"yes":col, "no":"-"}) 

这篇关于我想将dataframe的值替换为python中的列名.我应该怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆