[英]I am trying to get the values associated with name in my json output in python. I dont know how to do it
[英]I want to replace values of dataframe as a column name in python. How am I suppose to do that?
我想使用循环转换以下值。
{'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 (链接到数据框)
我已经对单个行使用了“地图”。 但我想循环播放。
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请帮助我使用循环。
您可以使用以下解决方案:
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":"-"})
尝试这个..
>>> df
A B C D
Id
2 no no no yes
3 yes yes yes no
4 yes no yes no
5 no yes no yes
>>> df.loc[:, 'A':'D'].replace('yes', pd.Series(df.columns, df.columns)).replace('no', '-')
A B C D
Id
2 - - - D
3 A B C -
4 A - C -
5 - B - D
@ – Quang Hoang提到的另一种解决方案。
>>> for col in 'ABCD':
... df[col] = df[col].map({'yes':col, 'no':'-'})
...
>>> df
A B C D
Id
2 - - - D
3 A B C -
4 A - C -
5 - B - D
要么
>>> for cell in df[['A','B','C','D']].columns:
... df[cell].replace({'yes':col, 'no':'-'}, inplace=True)
...
>>> df
A B C D
Id
2 - - - D
3 D D D -
4 D - D -
5 - D - D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.