python - 大熊猫中清理数据框的面向对象模式
问题描述
我需要帮助以面向对象模式编写我的 python 代码。我正在尝试使用熊猫标记数据框中的列值。有人可以帮助我如何开始或向我推荐一些资源吗?如何声明一个全局变量并指定温度和湿度的范围,然后编写一个函数来标记超出范围的值?
这是我的代码:
import pandas as pd
filename = 'data.csv'
#Read the dataframe and display the column names in the dataframe
df = pd.read_csv('data.csv', encoding="Latin",low_memory=False, keep_default_na = False, parse_dates = True)
#Condition: If the values are less than -50 and greater than 50, flag the values
for index, row in df.iterrows():
if (row['Temperature'] < -50) | (row['Temperature (C)'] > 50):
print index, row ['Temperature']
#Condition: If the values are less than 0 and greater than 100, flag the values
for index, row in df.iterrows():
if (row['Humidity'] < 0.0) | (row['Humidity'] > 100):
print index, row ['Humidity']
解决方案
如果您只想显示满足某些条件的行,您可以使用查询方法。
print df.query('Temperature < -50 | Temperature > 50')
如果要在新列中添加标志,请使用 df.eval
# init the new column
df['Flag']= 'Inside'
# update based on the test
df.loc[df.eval('Temperature < -50 | Temperature > 50'), 'Flag'] = 'Outside'