【发布时间】:2025-11-23 08:50:01
【问题描述】:
我有一个数据框,我想根据条件替换该列中的一些值。我的数据框看起来像这样
ID customer_name arrival_month leaving_month
1524 ABC 201508 201605
1185 XYZ 201701 201801
8456 IJK 201801 201902
我在这里尝试一个简单的操作。我想通过 currentmonth 值 = 201802 更改离开月列中的值,其中离开月 > 201802。 我已经通过 .loc 尝试过,它给出了以下错误。
df.loc[(df['leaving_month'] > 201802)] = 201802
KeyError: 'leaving_month'
我也试过 np.where 也报错。
df['leaving_month']=np.where(df['leaving_month']>currentmonth, currentmonth)
KeyError: 'leaving_month'
我也尝试过暴力循环
for o in range(len(df)):
if(df.loc[o,'leaving_month']>currentmonth):
df.loc[o,'leaving_month']=currentmonth
IndexingError: Too many indexers
有人可以指出我正确的方向或找出我做错了什么或提出更好的解决方案吗?这是一个非常简单的问题,但不知何故我没有解决。
【问题讨论】:
-
是的,这是帖子中的错字。不是实际代码
-
KeyError: 'leaving_month'明确表示df没有'leaving_month'列。df.columns.tolist()的输出是什么? -
我在您更新的示例中没有收到错误。不过还是有一个错误……看我的回答。
标签: python python-3.x python-2.7 pandas dataframe