gpt4 book ai didi

python - 如何根据条件替换 Pandas 数据框中任何位置的值?

转载 作者:太空宇宙 更新时间:2023-11-03 12:37:23 25 4
gpt4 key购买 nike

关于替换某些行或列或特定值的问题太多了,但我还没有找到我要找的东西。想象一下这样的数据框,

          a         b         c         d
a 0.354511 0.416929 0.704512 0.598345
b 0.948605 0.473364 0.154856 0.637639
c 0.250829 0.130928 0.682998 0.056049
d 0.504516 0.880731 0.216192 0.314724

现在我想用其他东西替换基于条件的所有值(无论它们在哪一列或哪一行)。假设我想用 np.nan 替换所有 < 0.5 的值。我尝试了几件事,但没有任何效果(即什么也没发生,数据框保持不变)。

此处示例代码:

frame = pd.DataFrame(np.random.rand(4,4),index=['a','b','c','d'], columns=['a','b','c','d'])
print frame
for row,col in enumerate(frame):
frame.replace(frame.ix[row,col]<0.5,np.nan,inplace=True)
print frame

for row,col in enumerate(frame):
if frame.ix[row,col]<=0.5:
M.ix[row,col]=np.nan
print M

但最后,

          a         b         c         d
a 0.600701 0.823570 0.159012 0.615898
b 0.234855 0.086080 0.950064 0.982248
c 0.440625 0.960078 0.191975 0.598865
d 0.127866 0.537867 0.434326 0.507635
a b c d
a 0.600701 0.823570 0.159012 0.615898
b 0.234855 0.086080 0.950064 0.982248
c 0.440625 0.960078 0.191975 0.598865
d 0.127866 0.537867 0.434326 0.507635

- 它们是相同的,没有 NaN 而不是小值。问题出在哪里?

最佳答案

执行此操作的 pandas 方法是 wheremask

where 保留条件为 True
的数据帧值可选的第二个参数是要替换的值

frame.where(frame < .5, -9)

a b c d
a 0.354511 0.416929 -9.000000 -9.000000
b -9.000000 0.473364 0.154856 -9.000000
c 0.250829 0.130928 -9.000000 0.056049
d -9.000000 -9.000000 0.216192 0.314724

或者姐妹方法

mask 保留条件为 False
的数据帧值可选的第二个参数是要替换的值

frame.mask(frame < .5, -9)

a b c d
a -9.000000 -9.000000 0.704512 0.598345
b 0.948605 -9.000000 -9.000000 0.637639
c -9.000000 -9.000000 0.682998 -9.000000
d 0.504516 0.880731 -9.000000 -9.000000

numpy.where
我们可以使用 numpy 来达到非常相似的效果

pd.DataFrame(
np.where(frame < .5, df, -9),
frame.index, frame.columns)

a b c d
a 0.354511 0.416929 -9.000000 -9.000000
b -9.000000 0.473364 0.154856 -9.000000
c 0.250829 0.130928 -9.000000 0.056049
d -9.000000 -9.000000 0.216192 0.314724

朴素时间测试

enter image description here

关于python - 如何根据条件替换 Pandas 数据框中任何位置的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42939839/

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