我有一个包含4列的数据帧,前3列是数值变量,表示最后一列变量的特征,最后一列是字符串。
我想通过groupby函数将最后一个字符串列与前3列合并在一起。然后它就可以工作了(我的意思是,共享前三列记录的相同特性的字符串已经成功合并)
之前数据帧的长度为1200,合并后的数据帧的长度为1100。我发现后面的df是多索引的。它只包含2列。(分层索引)因此,我通过生成的升序数字列表尝试了reindex方法。遗憾的是,我失败了。
df1.columns
*[Out]Index(['time', 'column','author', 'text'], dtype='object')
series = df1.groupby(['time', 'column','author'])
['body_text'].sum()#merge the last column by the first 3 columns
dfx = series.to_frame()# get the new df
dfx.columns
*[Out]Index(['author', 'text'], dtype='object')
len(dfx)
*[Out]1100
indexs = list(range(1100))
dfx.reindex(index = indexs)
*[Out]Exception: cannot handle a non-unique multi-index!
发布于 2019-05-08 13:34:20
此处Reindex
不是必需的,最好使用DataFrame.reset_index
或将参数as_index=False
添加到DataFrame.groupby
dfx = df1.groupby(['time', 'column','author'])['body_text'].sum().reset_index()
或者:
dfx = df1.groupby(['time', 'column','author'], as_index=False)['body_text'].sum()
https://stackoverflow.com/questions/56042038
复制相似问题