gpt4 book ai didi

python - Pandas dataframe 按一些值填充

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:58 24 4
gpt4 key购买 nike

我有这个数据

import numpy as np
import pandas as pd
group = {'gender': ['male', 'female', 'female', 'male', 'female', 'male', 'male'],
'height': [175, 168, np.nan, 170, 167, np.nan, 190],
}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
df = pd.DataFrame(group, index=labels)
df2 = df.groupby('gender')['height'].mean()

我想用 df2 的平均值填充 nan

最佳答案

您可以使用 groupby + transformmean。然后用结果系列fillna

means = df.groupby('gender')['height'].transform('mean')
df['height'] = df['height'].fillna(means)

print(df)

gender height
a male 175.000000
b female 168.000000
c female 167.500000
d male 170.000000
e female 167.000000
f male 178.333333
g male 190.000000

关于python - Pandas dataframe 按一些值填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51570723/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com