Python 熊猫-使用groupby将列与字符串组合-TypeError消息存在问题
我有一个非常简单的案例,出于某种原因,给我带来了问题 我正在组合多个数据帧。因此,我通常会有相同的键,但每个键值的注释不同Python 熊猫-使用groupby将列与字符串组合-TypeError消息存在问题,python,pandas,pandas-groupby,consolidation,Python,Pandas,Pandas Groupby,Consolidation,我有一个非常简单的案例,出于某种原因,给我带来了问题 我正在组合多个数据帧。因此,我通常会有相同的键,但每个键值的注释不同 KeyValue Comment 1235 This is okay 444 Problems here 1235 Investigate further 我正在尝试重复删除键,但通过将它们合并到一个comments字段来保留所有注释。我想要的输出: KeyValue Comment 1
KeyValue Comment
1235 This is okay
444 Problems here
1235 Investigate further
我正在尝试重复删除键,但通过将它们合并到一个comments字段来保留所有注释。我想要的输出:
KeyValue Comment
1235 This is okay | Investigate further
444 Problems here
我试过:
newdf = olddf.groupby('KeyValue')['Comment'].apply(lambda x: ' | '.join(x)).reset_index()
但当我这么做的时候,我会
"TypeError: sequence item 0: expected str instance, float found"
我在这里看到了与我类似的问题(这是我获得原始代码的地方),但不确定为什么会出现此错误或如何解决它。任何帮助都将不胜感激 我将您的键值转换为字符串,它可以工作:
import pandas as pd
mydata = pd.DataFrame([['KeyValue','Comment'],
[1235,'This is okay'],
[444,'Problems here'],
[1235,'Investigate further']])
mydata.columns = mydata.iloc[0]
mydata = mydata[1:]
print(mydata)
newdf = mydata.groupby(str('KeyValue'))['Comment'].apply(lambda x: ' | '.join(x)).reset_index()
print(newdf)
0 KeyValue Comment
1 1235 This is okay
2 444 Problems here
3 1235 Investigate further
KeyValue Comment
0 444 Problems here
1 1235 This is okay | Investigate further
也许可以尝试
olddf.astype(str).groupby('KeyValue')['Comment']。apply('|'.join)。reset_index()
。。?(注意-join
不需要lambda语法)尝试lambda x:“|”。join(x.dropna())
。我认为缺少的值会把你搞砸,因为NaN
是一个浮点数。或者,您可以执行olddf[olddf['Comment'].notnull()].groupby…
@ALollz这就是问题所在。由于缺少值而再次出错:)谢谢!你是在一根线对一根线。。这不会有任何作用的。。?