gpt4 book ai didi

python - 选择行并替换值小于 Pandas 中特定值的列

转载 作者:太空宇宙 更新时间:2023-11-04 04:36:40 25 4
gpt4 key购买 nike

我有一个包含 30 个数字列的数据框。我想选择任何列中值小于例如 50 的行,并将其替换为该行的平均值。我尝试执行以下操作,但没有成功。

dataset.where((dataset[:]>=50).any(axis=1), dataset.mean(axis=1), axis=1, inplace=True)

最佳答案

您需要 axis=0 来为所有列设置一个值。

您还需要 pd.DataFrame.mask 而不是 pd.DataFrame.where 来更改指定条件为 True 的值。

df = pd.DataFrame([[75, 100, 65],
[25, 25, 30],
[55, 90, 45],
[55, 90, 75]])

df.mask((df < 50).any(axis=1), df.mean(axis=1), axis=0, inplace=True)

print(df)

0 1 2
0 75.000000 100.000000 65.000000
1 26.666667 26.666667 26.666667
2 63.333333 63.333333 63.333333
3 55.000000 90.000000 75.000000

关于python - 选择行并替换值小于 Pandas 中特定值的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51539617/

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