【问题标题】:Add categorical column to data frame and match categories with existing categorical column将分类列添加到数据框并将类别与现有分类列匹配
【发布时间】:2020-07-04 07:00:51
【问题描述】:

我有两个数据框,其中包含在逻辑上相互关联并包含相同数量的类别的类别列(df1 中的类别 1 df2 中的类别 1,df1 中的类别 2 类别 2在 df2 等中。)。数据帧的长度不同,并且行没有排序,所以我不能简单地重新排序和连接它们。

我想将 df2 的分类变量添加到 df1,以便两个分类列的类别匹配。

这是一个例子:

import pandas as pd

foo = pd.Categorical(values=[0,1,2,3],categories=[0,1,2,3],ordered=True)
bar = pd.Categorical(values=['b','c','b','a','d','a'],categories=['a','b','c','d'],ordered=True)

df_1 = pd.DataFrame({'foo':foo})
df_2 = pd.DataFrame({'bar':bar})
  foo
0   0
1   1
2   2
3   3
  bar
0   b
1   c
2   b
3   a
4   d
5   a

我想得到:

  foo bar
0   0   a
1   1   b
2   2   c
3   3   d

编辑

当两个数据框包含额外的列时,该解决方案也应该有效,例如:

import pandas as pd

foo_1 = pd.Categorical(values=[0,1,2,3],categories=[0,1,2,3],ordered=True)
foo_2 = pd.Series(['x','y','z','x'])

bar_1 = pd.Categorical(values=['b','c','b','a','d','a'],categories=['a','b','c','d'],ordered=True)
bar_2 = pd.Series([0.1,0.2,0.3,0.3,0.5,0.6])

df_1 = pd.DataFrame({'foo_1':foo_1,'foo_2':foo_2})
df_2 = pd.DataFrame({'bar_1':bar_1,'bar_2':bar_2})

【问题讨论】:

  • 是的,两个分类变量都是有序的,并且类别相互对应。

标签: python pandas


【解决方案1】:

当您使用mapSeries 对齐时,对齐与系列索引,这就是为什么df_1 中的前4 行映射到df_2 中的前4 行。相反,您需要确保在分类代码上对齐。

Series.cat.categories 将按顺序列出类别。您可以使用枚举的第二个分类列创建一个简单的字典,并映射第一个分类的代码。

d = dict(enumerate(df_2['bar'].cat.categories))
df_1['bar'] = df_1['foo'].cat.codes.map(d)

#  foo bar
#0   0   a
#1   1   b
#2   2   c
#3   3   d

【讨论】:

    【解决方案2】:

    您可以将索引带入变量并像这样合并两个数据集:

    df_1.merge(df_2.reset_index(), left_on=['foo'], right_on=['index'], how='left')
    

    结果:

        foo index   bar
    0   0   0       b
    1   1   1       c
    2   2   2       b
    3   3   3       a
    
    

    【讨论】:

      猜你喜欢
      • 2016-01-25
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      • 2022-06-21
      • 2018-06-23
      • 2019-01-30
      • 2020-08-03
      • 1970-01-01
      相关资源
      最近更新 更多