gpt4 book ai didi

python - 根据条件从 DataFrame 中删除值

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

需要强调的是,这不是删除行。

在一个简单的例子中,我有一个来自传感器的文件:

import pandas as pd

df = pd.DataFrame({'Date': ['15/03/2019 10:00:11.000', '15/03/2019 10:00:12.000' , '15/03/2019 10:00:13.000'],
'Pressure' : [-0.162, -0.162, 1.456],
'Conductivity': [-0.001, -0.001, 7.45],
'Water_Temperature': [7.555, 7.555, 8.22],
'Water_Salinity': [0.004, 0.004, 7.63]})

我需要删除 'Pressure' <1 行中的值,最好不要删除 'Date'(有关缺失值数量和不正确数据的信息也很重要)。

我试着用 .where 方法做到这一点:

condition = df['Pressure'] < 1
droped_df = df.where(condition ," " )

但它什么也没做。我也不知道如何将条件扩展到其余列,特别是如果原始文件中有更多列。

最终效果应该是这样的:

df = pd.DataFrame({'Date': ['15/03/2019 10:00:11.000', '15/03/2019 10:00:12.000' , '15/03/2019 10:00:13.000'],
'Pressure' : [ , , 1.456],
'Conductivity': [ , , 7.45],
'Water_Temperature': [ , , 8.22],
'Water_Salinity': [ , , 7.63]})

感谢您的关注!

最佳答案

使用 DataFrame.mask 设置所有列,而无需先由 DataFrame.iloc 按条件选择:

df.iloc[:, 1:] = df.iloc[:, 1:].mask(df['Pressure'] < 1) 
print (df)
Date Pressure Conductivity Water_Temperature \
0 15/03/2019 10:00:11.000 NaN NaN NaN
1 15/03/2019 10:00:12.000 NaN NaN NaN
2 15/03/2019 10:00:13.000 1.456 7.45 8.22

Water_Salinity
0 NaN
1 NaN
2 7.63

如果真的需要空格 - 获取数字和字符串的混合值,所以所有数字操作都失败:

df.iloc[:, 1:] = df.iloc[:, 1:].mask(df['Pressure'] < 1, '') 
print (df)
Date Pressure Conductivity Water_Temperature \
0 15/03/2019 10:00:11.000
1 15/03/2019 10:00:12.000
2 15/03/2019 10:00:13.000 1.456 7.45 8.22

Water_Salinity
0
1
2 7.63

关于python - 根据条件从 DataFrame 中删除值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57090986/

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