【问题标题】:Pandas - Ignoring empty values when concatenating grouped rowsPandas - 连接分组行时忽略空值
【发布时间】:2019-03-18 03:38:57
【问题描述】:

我正在尝试根据列值对数据框进行分组,并且我想连接(连接)其他列中的值。

我正在做类似的事情 -

df_combined = df_combined.groupby('UC').agg({'LO Number': ', '.join,
                                             'K Code': ', '.join})

但是,这给了我一些 nan 值,而 K Code 列没有值。所以结果看起来像

K Code

K0016, K0068, nan, nan, A0046

nan, nan, nan

如何摆脱K Code 列中的这些 nan 值?此外,有没有办法获得第三列,其中包含K Code 列中存在的值的数量。例如。对于上述情况,

Count

3   

0

编辑:示例数据 -

UC      LO Number      K Code
C001     C001.1        K0068
C001     C001.2        K0372
C002     C002.1        
C002     C002.3        K0032
C002     C002.5          

谢谢! :)

【问题讨论】:

  • 您想向我们展示您的样本数据吗?

标签: python python-3.x pandas dataframe


【解决方案1】:

您可以尝试将lambdaagg 一起使用,但这会创建多重索引

既然你 nan 是 nan 在下面运行之前请替换

df=df.replace({'nan':np.nan})


df_combined.groupby('UC').agg({'LO Number': ', '.join,
                                             'K Code': [lambda x : ', '.join(y for y in x if y==y),'count']})

如果你不想要多重索引

df_combined.assign(count=df_combined['K Code']).
         groupby('UC').agg({'LO Number': ', '.join,
                           'K Code': lambda x : ', '.join(y for y in x if y==y),
                            'count':'count'})

【讨论】:

  • @harry04 确保你的 nan 是 np.nan 而不是字符串中的“nan”
  • 我认为它是“nan”而不是 np.nan(如果我没记错,它会显示为 NaN)。
  • @harry04 在我的代码 df = df.替换({‘nan’:np.nan})
猜你喜欢
  • 2019-04-11
  • 1970-01-01
  • 1970-01-01
  • 2015-03-20
  • 1970-01-01
  • 1970-01-01
  • 2018-11-12
  • 1970-01-01
  • 2019-05-07
相关资源
最近更新 更多