为什么基于条件的过滤会导致 pandas 中的 DataFrame 为空?

问题描述 投票:0回答:2

我正在使用 pandas 在 Python 中处理 DataFrame,并且尝试应用多个条件来根据多列中的温度值过滤行。然而,在应用我的条件并使用

dropna()
后,即使我期望某些数据满足这些条件,我最终也会得到零行。

目标是与环境温度+40 C 进行比较,如果值大于此值,则将其替换为 NaN。否则,保持原值``

这是我的 DataFrame 的示例以及我正在应用的条件:

data = {
    'Datetime': ['2022-08-04 15:06:00', '2022-08-04 15:07:00', '2022-08-04 15:08:00', 
                 '2022-08-04 15:09:00', '2022-08-04 15:10:00'],
    'Temp1': [53.4, 54.3, 53.7, 54.3, 55.4],
    'Temp2': [57.8, 57.0, 87.0, 57.2, 57.5],
    'Temp3': [59.0, 58.8, 58.7, 59.1, 59.7],
    'Temp4': [46.7, 47.1, 80, 46.9, 47.3],
    'Temp5': [52.8, 53.1, 53.0, 53.1, 53.4],
    'Temp6': [50.1, 69, 50.3, 50.3, 50.6],
    'AmbientTemp': [29.0, 28.8, 28.6, 28.7, 28.9]
}
df1 = pd.DataFrame(data)
df1['Datetime'] = pd.to_datetime(df1['Datetime'])
df1.set_index('Datetime', inplace=True)

代码:

temp_cols = ['Temp1', 'Temp2', 'Temp3', 'Temp4', 'Temp5', 'Temp6']
ambient_col = 'AmbientTemp'

condition = (df1[temp_cols].lt(df1[ambient_col] + 40, axis=0))

filtered_df = df1[condition].dropna()
print(filtered_df.shape)

回复:

(0, 99)

问题:

尽管期望得到满足条件的有效数据,但在应用过滤器并删除 NaN 值后,生成的 DataFrame 为空。可能是什么原因导致此问题?我该如何解决?


python pandas dataframe numpy
2个回答
0
投票

您的条件是一个 DataFrame,您应该使用

any
/
all
:

进行聚合
condition = (df1[temp_cols].lt(df1[ambient_col] + 40, axis=0)).any(axis=1)

0
投票

用途:

condition = (df1[temp_cols].lt(df1[ambient_col] + 40, axis=0))

df1[temp_cols] = df1[temp_cols].where(condition)
© www.soinside.com 2019 - 2024. All rights reserved.