【问题标题】:compare column value with another value in a dataframe (weather data forecast)将列值与数据框中的另一个值进行比较(天气预报)
【发布时间】:2021-11-28 14:40:23
【问题描述】:

我需要将我的列值(113 839 个值)与一个类别(位置)的平均值(降雨量)(44 个值)进行比较。如果它高于我的平均值,则应将其替换为平均值。我的 foreach 不起作用:

df_rainfall = pd.DataFrame(weather_train_data_total.groupby(['Location'])['Rainfall'].mean())

for column in weather_train_data_total[['Location']]:
result = weather_train_data_total[column]
print(result)
if result.equals(df_rainfall['Location']):
    result = df_rainfall['Rainfall']

【问题讨论】:

  • 请发布 df.head(10) 调用,以便我们查看数据的样子
  • 我添加了一张图片@bguest

标签: python pandas dataframe numpy foreach


【解决方案1】:

没有数据,提供帮助总是很棘手,但您可以尝试适应这一点:

# calculate and assign the average value for each group
df["mean_val"] = df.groupby("Location")["Rainfall"].transform("mean")

# identify rows in which the value is above the average
relevant_rows = df["mean_val"] < df["Rainfall"]

# replace these values with their corresponding average
df.loc[relevant_rows, ["Rainfall"]] = df.loc[relevant_rows, ["mean_val"]]["mean_val"]
df

【讨论】:

    猜你喜欢
    • 2018-03-14
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    相关资源
    最近更新 更多