合并数据框时出现KeyError

时间:2019-09-26 11:08:30

标签: python dataframe join self-join

我有一张带有客户购买历史记录的表。需要填充一个新列,以在历史数据中指示活动的第一天和最后一天。

输入数据格式:Index(['date_first', 'unique_id', 'event', 'price', 'product_id', 'category','month', 'buy', 'Bought_Before'], dtype='object')

df_first=df.sort_values(by=['date']).drop_duplicates(subset='unique_id', keep='first')    
df_last=df.sort_values(by=['date']).drop_duplicates(subset='unique_id', keep='last')
#renaming date column as first_Active_Day and last_active_Day to avoid #confusion in merge
df_first.columns=['first_active_day', 'unique_id', 'event', 'price', 'product_id', 'category','month', 'buy', 'Bought_Before']

df_first.columns=['last_active_day', 'unique_id', 'event', 'price', 'product_id', 'category','month', 'buy', 'Bought_Before']

df_result = df.merge(df,df_first['first_active_day'],df_last['last_active_day'], on='unique_id')

我需要日期-第一和最后一个活动日,因为新列已添加到原始数据框。我正在创建中间数据框以获取第一个和最后一个活动日。请让我知道是否可以通过简单或单个步骤完成。感谢您的帮助。谢谢!

错误日志:(在下面)

文件“”,第1行,在     df_result = df3.merge(df3,df_first,on ='unique_id')

文件“ C:\ ProgramData \ Anaconda3 \ lib \ site-packages \ pandas \ core \ frame.py”,合并行6868     复制=复制,指标=指标,验证=验证)

文件“ C:\ ProgramData \ Anaconda3 \ lib \ site-packages \ pandas \ core \ reshape \ merge.py”,合并中的第48行     返回op.get_result()

文件“ C:\ ProgramData \ Anaconda3 \ lib \ site-packages \ pandas \ core \ reshape \ merge.py”,行546,在get_result中     join_index,left_indexer,right_indexer = self._get_join_info()

_get_join_info中的行“ C:\ ProgramData \ Anaconda3 \ lib \ site-packages \ pandas \ core \ reshape \ merge.py”,第756行     right_indexer)= self._get_join_indexers()

文件“ C:\ ProgramData \ Anaconda3 \ lib \ site-packages \ pandas \ core \ reshape \ merge.py”,行_get_join_indexers中的735行     how = self.how)

文件“ C:\ ProgramData \ Anaconda3 \ lib \ site-packages \ pandas \ core \ reshape \ merge.py”,行1142,在_get_join_indexers中     如果如何=='左':

文件“ C:\ ProgramData \ Anaconda3 \ lib \ site-packages \ pandas \ core \ generic.py”,行1478,非零     .format(self。 class name ))

ValueError:DataFrame的真值不明确。使用a.empty,a.bool(),a.item(),a.any()或a.all()。

0 个答案:

没有答案