【问题标题】:Pandas join with categorical indicesPandas 加入分类索引
【发布时间】:2021-11-25 07:47:52
【问题描述】:

尝试使用分类索引加入 Pandas DataFrame 对象时,我得到了意想不到的结果。这是最小的可重现示例(从我的实际用例中总结出来):

shape_categories=['square', 'circle']
color_categories=['red', 'blue', 'green']

test_a = pd.DataFrame({
    'shape': pd.Categorical(['square', 'circle'], categories=shape_categories, ordered=True),
    'color': pd.Categorical(['red', 'blue'], categories=color_categories, ordered=True),
    'value_a': [1.0, 2.0]
})
test_a.set_index(['shape', 'color'], inplace=True)

test_b = pd.DataFrame({
    'shape': pd.Categorical(['square', 'square', 'circle', 'circle'], categories=shape_categories, ordered=True),
    'color': pd.Categorical(['red', 'blue', 'red', 'blue'], categories=color_categories, ordered=True),
    'value_b': [10.0, np.nan, np.nan, 40.0]
})
test_b.set_index(['shape', 'color'], inplace=True)

test_a.join(test_b, how='left')

我期待

shape color value_a value_b
square red 1.0 10.0
circle blue 2.0 40.0

但我得到了

shape color value_a value_b
square red 1.0 10.0
circle blue 2.0 NaN

我错过了什么?我试图小心保持分类变量的 dtypes 完全相同。

【问题讨论】:

  • 你用的是什么版本?我在 Pandas 1.3.1 上运行,它运行良好。我可能误解了你的帖子,所以请分享你的预期输出
  • 刚刚在上面进行了编辑,以便更清楚地了解我的怀疑。我正在使用熊猫 v1.1.3。现在升级看看是否有帮助。
  • 呃。升级到 1.3.3 就成功了。谢谢。
  • 为了后代,这里是错误报告:github.com/pandas-dev/pandas/issues/38502 Fixed in 1.3

标签: python pandas categorical-data


【解决方案1】:

您需要指定所有要合并的索引,否则 pandas 只会使用第一个。所以在你的情况下:

test_a.join(test_b, how='left', on = ['shape', 'color'])

应该会产生预期的结果。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-05-04
  • 1970-01-01
  • 1970-01-01
  • 2014-07-10
  • 2018-08-28
  • 2020-05-28
  • 2019-09-14
  • 2012-12-29
相关资源
最近更新 更多