Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

python - Replace values in a pandas dataframe with a dict

I'll have a pandas dataframe and looking for a method to replace the values for column = c with the mean value for column = a and column = b.

Being a novice at Python, I have checked the replace function, and the possibility to create a dict to perform the replacement. My failed attempt is visible below.

If anyone has any suggestions I would be thrilled.

df = pd.DataFrame({'column': ['a', ' b', 'a', 'b', 'b', 'a', 'b', 'c', 'd' ], 'value': range(0,9)})

dict = {"(df[df['column'] == 'c']['value'].values)": "df[df['column'] == 'a']['value'].mean()"}

df.replace(dict)

question from:https://stackoverflow.com/questions/65938407/replace-values-in-a-pandas-dataframe-with-a-dict

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can set and select column value by DataFrame.loc:

df.loc[df['column'] == 'c', 'value'] = df.loc[df['column'] == 'a', 'value'].mean()
print (df)
  column     value
0      a  0.000000
1      b  1.000000
2      a  2.000000
3      b  3.000000
4      b  4.000000
5      a  5.000000
6      b  6.000000
7      c  2.333333
8      d  8.000000

Or if need test multiple values use Series.isin:

df.loc[df['column'] == 'c', 'value'] = df.loc[df['column'].isin(['a','b']), 'value'].mean()
print (df)
  column     value
0      a  0.000000
1      b  1.000000
2      a  2.000000
3      b  3.000000
4      b  4.000000
5      a  5.000000
6      b  6.000000
7      c  3.333333
8      d  8.000000

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...