【问题标题】:Pandas - Using groupby to combine columns with strings - problem with TypeError messagePandas - 使用 groupby 将列与字符串组合 - TypeError 消息的问题
【发布时间】:2020-06-17 09:58:04
【问题描述】:

我有一个非常简单的案例,出于某种原因,它给我带来了问题。

我正在组合多个数据框。因此,我经常有相同的键,但每个键值的 cmets 不同。

KeyValue       Comment
1235           This is okay
444            Problems here
1235           Investigate further

我正在尝试对密钥进行重复数据删除,但通过将所有 cmets 合并到一个 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" 

我在这里看到了与我类似的问题(这是我获得原始代码的地方),但不知道为什么我会收到此错误或如何解决它。任何帮助,将不胜感激。

【问题讨论】:

  • 也许试试olddf.astype(str).groupby('KeyValue')['Comment'].apply(' | '.join).reset_index() ..? (注意 - 你不需要 join 的 lambda 语法)
  • 试试lambda x: ' | '.join(x.dropna())。我认为缺失值会让您感到困惑,因为 NaN 是一个浮点数。或者,你可以做olddf[olddf['Comment'].notnull()].groupby...
  • @ALollz 这就是问题所在。再次被缺失值绊倒:) 谢谢!

标签: python pandas pandas-groupby consolidation


【解决方案1】:

我将您的键值转换为字符串,它可以工作:

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

【讨论】:

  • 你正在将一个字符串转换为一个字符串..这不会做任何事情..?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 2018-11-05
  • 2020-04-18
  • 2020-01-15
  • 2013-07-24
  • 2015-11-14
相关资源
最近更新 更多