以下Python代码出现错误KeyError: 'x1_diff'的原因:# 创建两个Dataframe df1 = pd.DataFrame({'m1': [1, 2, 3], 'm2': ['a', 'b', 'c'], 'x1': [10, 20, 30], 'x2': [100, 200, 300]}) df2 = pd.DataFrame({'m2': ['c', 'b', 'a'], 'm1': [3, 2, 1], 'x2': [350, 250, 150], 'x1': [35, 25, 15]}) # 按照相同维度字段m1、m2将两个Dataframe进行合并 merged_df = pd.merge(df1, df2, on=['m1', 'm2']) # 计算两个Dataframe的差值 merged_df['x1_diff'] = merged_df['x1_y'] - merged_df['x1_x'] merged_df['x2_diff'] = merged_df['x2_y'] - merged_df['x2_x'] # 计算x1和x2字段的值 merged_df['x1_value'] = merged_df[['x1_x', 'x1_y']].apply(lambda x: x['x1_diff'] / x['x1_x'], axis=1) merged_df['x2_value'] = merged_df[['x2_x', 'x2_y']].apply(lambda x: x['x2_diff'] / x['x2_x'], axis=1) # 筛选出x1和x2字段计算出来的大于0的所有值 positive_x1 = merged_df.loc[merged_df['x1_value'] > 0, 'x1_value'].values positive_x2 = merged_df.loc[merged_df['x2_value'] > 0, 'x2_value'].values # 计算中位数和第二四分位数 x1_median = np.median(positive_x1) x1_q2 = np.percentile(positive_x1, 75) x1_q4 = np.percentile(positive_x1, 25) x2_median = np.median(positive_x2) x2_q2 = np.percentile(positive_x2, 75) x2_q4 = np.percentile(positive_x2, 25) print('x1 中位数:', x1_median) print('x1 第二四分位数:', x1_q2, x1_q4) print('x2 中位数:', x2_median) print('x2 第二四分位数:', x2_q2, x2_q4)
时间: 2023-08-06 07:05:21 浏览: 426
dbf.rar_arcgis_arcgis python_site:www.pudn.com
这个错误是因为在计算`merged_df['x1_diff']`时,使用了不正确的列名。应该使用`merged_df['x1_y'] - merged_df['x1_x']`来计算,因为这是合并后的两个Dataframe中`x1`列的差值。正确的代码如下:
```
# 创建两个Dataframe
df1 = pd.DataFrame({'m1': [1, 2, 3], 'm2': ['a', 'b', 'c'], 'x1': [10, 20, 30], 'x2': [100, 200, 300]})
df2 = pd.DataFrame({'m2': ['c', 'b', 'a'], 'm1': [3, 2, 1], 'x2': [350, 250, 150], 'x1': [35, 25, 15]})
# 按照相同维度字段m1、m2将两个Dataframe进行合并
merged_df = pd.merge(df1, df2, on=['m1', 'm2'])
# 计算两个Dataframe的差值
merged_df['x1_diff'] = merged_df['x1_y'] - merged_df['x1_x']
merged_df['x2_diff'] = merged_df['x2_y'] - merged_df['x2_x']
# 计算x1和x2字段的值
merged_df['x1_value'] = merged_df[['x1_x', 'x1_y']].apply(lambda x: x['x1_diff'] / x['x1_x'], axis=1)
merged_df['x2_value'] = merged_df[['x2_x', 'x2_y']].apply(lambda x: x['x2_diff'] / x['x2_x'], axis=1)
# 筛选出x1和x2字段计算出来的大于0的所有值
positive_x1 = merged_df.loc[merged_df['x1_value'] > 0, 'x1_value'].values
positive_x2 = merged_df.loc[merged_df['x2_value'] > 0, 'x2_value'].values
# 计算中位数和第二四分位数
x1_median = np.median(positive_x1)
x1_q2 = np.percentile(positive_x1, 75)
x1_q4 = np.percentile(positive_x1, 25)
x2_median = np.median(positive_x2)
x2_q2 = np.percentile(positive_x2, 75)
x2_q4 = np.percentile(positive_x2, 25)
print('x1 中位数:', x1_median)
print('x1 第二四分位数:', x1_q2, x1_q4)
print('x2 中位数:', x2_median)
print('x2 第二四分位数:', x2_q2, x2_q4)
```
阅读全文