[英]pandas change values in dataframe with iterrows()?
我正在尝试根据条件在单独的 df 列中用1
或0
“标记”一些数据,但可以使用一些提示......
编辑,这个问题不是在数据帧中查找数据,而是试图根据行条件寻找解决方案修改数据帧中每一行的值。
组成数据:
import pandas as pd
import numpy as np
rows,cols = 8760,3
data = np.random.rand(rows,cols)
tidx = pd.date_range('2019-01-01', periods=rows, freq='1T')
df = pd.DataFrame(data, columns=['cooling_sig','heating_sig','economizer_sig'], index=tidx)
这是我的应用程序的一些额外参数和列:
# params for air handling unit (ahu)
ahu_min_oa = .2
# make columns out of params
df['ahu_min_oa'] = ahu_min_oa
df['heating_mode'] = 0
df['econ_mode'] = 0
df['econ+mech_cooling'] = 0
df['mech_cooling'] = 0
一个处理数据的函数,但它不起作用。 除了敲击数据框的每一行之外,任何更好的做法都非常感谢。 我正在尝试根据条件“标记”值为1
的模式。 例如,对于数据中的每一行,如果heating_sig
大于零,则heating_mode
将为True 或1
。
def data_preprocess(dataframe):
for index, row in dataframe.iterrows():
# OS1, the AHU is heating
if row.heating_sig > 0:
row['heating_mode'] = 1
# OS2, the AHU is using free cooling only
if row.economizer_sig > row.ahu_min_oa and row.cooling_sig == 0:
row['econ_mode'] = 1
# OS3, the AHU is using free and mechanical cooling
if row.economizer_sig > row.ahu_min_oa and row.cooling_sig > 0:
row['econ+mech_cooling'] = 1
# OS4, the AHU is using mechanical cooling only
if row.economizer_sig <= row.ahu_min_oa and row.cooling_sig > 0:
row['mech_cooling'] = 1
return dataframe
抱歉,可能是一个奇怪的应用程序和问题,但感谢您提供任何提示。 我尝试标记一些数据不起作用,所有的value_counts()
都为零。
df['heating_mode'].value_counts()
df['mech_cooling'].value_counts()
df['econ_mode'].value_counts()
df['econ+mech_cooling'].value_counts()
您不需要(也不应该)遍历您的 DataFrame。
相反,请尝试:
df.loc[df["heating_sig"].eq(1), "heating_mode"] = 1
df.loc[df["economizer_sig"].gt(df["ahu_min_oa"]) & df["cooling_sig"].eq(0), "econ_mode"] = 1
df.loc[df["economizer_sig"].gt(df["ahu_min_oa"]) & df["cooling_sig"].gt(0), "econ+mech_cooling"] = 1
df.loc[df["economizer_sig"].le(df["ahu_min_oa"]) & df["cooling_sig"].gt(0), "mech_cooling"] = 1
可能有更有效的方法来做同样的事情,但如果你真的需要使用 iterrows(),那么请遵循以下方法:
def data_preprocess(dataframe):
for index, row in dataframe.iterrows():
# OS1, the AHU is heating
if row.heating_sig > 0:
dataframe.at[index, 'heating_mode'] = 1
# OS2, the AHU is using free cooling only
if row.economizer_sig > row.ahu_min_oa and row.cooling_sig == 0:
dataframe.at[index, 'econ_mode'] = 1
# OS3, the AHU is using free and mechanical cooling
if row.economizer_sig > row.ahu_min_oa and row.cooling_sig > 0:
dataframe.at[index, 'econ+mech_cooling'] = 1
# OS4, the AHU is using mechanical cooling only
if row.economizer_sig <= row.ahu_min_oa and row.cooling_sig > 0:
dataframe.at[index, 'mech_cooling'] = 1
return dataframe
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.