【问题标题】:adding up columns in pandas dataframe results in categorical index error将 pandas 数据框中的列相加会导致分类索引错误
【发布时间】:2018-08-18 03:04:44
【问题描述】:

我知道了。数据框:

ps_yd_1            $0^{th} - 25^{th}$  $25^{th} - 50^{th}$  \
ps_variable_1                                                   
$0^{th} - 25^{th}$             47.566800            23.441332   
$25^{th} - 50^{th}$            32.764905            40.947438   
$50^{th} - 75^{th}$            10.830286            21.435877   
$75^{th} - 100^{th}$           14.388537            33.796734   
ps_yd_1            $50^{th} - 75^{th}$  $75^{th} - 100^{th}$  
ps_variable_1                                                    
$0^{th} - 25^{th}$              21.237253              7.754615  
$25^{th} - 50^{th}$              8.634613             17.653044  
$50^{th} - 75^{th}$             14.684188             53.049650  
$75^{th} - 100^{th}$            13.072976             38.741753  

我想添加 2 列来创建一个新的:

df_hmp['a'] = df_hmp['$0^{th} - 25^{th}$'] + df_hmp['$25^{th} - 50^{th}$']

但我收到此错误:

*** TypeError: cannot insert an item into a CategoricalIndex that is not already an existing category

这是索引的样子:

CategoricalIndex(['$0^{th} - 25^{th}$', '$25^{th} - 50^{th}$',
                  '$50^{th} - 75^{th}$', '$75^{th} - 100^{th}$'],
                 categories=['$0^{th} - 25^{th}$', '$25^{th} - 50^{th}$', '$50^{th} - 75^{th}$', '$75^{th} - 100^{th}$'], ordered=True, name='ps_variable_1', dtype='category')

如何解决?

【问题讨论】:

  • 请提供易于复制到 IDE 中的示例数据。特别是在这种情况下,如果不进行大量重新配置,就很难重现导致此问题的条件。

标签: python pandas dataframe categorical-data


【解决方案1】:

数据框中的所有列和行都有分类索引。如果要添加另一列,必须先向分类索引添加另一个值。

让我们首先重新创建你的数据框:

df_hmp = pd.DataFrame([[47.566800 ,32.764905,10.830286,14.388537],
                 [23.441332,40.947438,21.435877,33.796734],
                 [21.237253,8.634613,14.684188,13.072976],
                 [7.75461,17.653044,53.049650,38.741753]]).T

idx = pd.CategoricalIndex(['$0^{th} - 25^{th}$', '$25^{th} - 50^{th}$',
               '$50^{th} - 75^{th}$', '$75^{th} - 100^{th}$'],
                categories=['$0^{th} - 25^{th}$', '$25^{th} - 50^{th}$',  
               '$50^{th} - 75^{th}$', '$75^{th} - 100^{th}$'], 
               ordered=True, name='ps_variable_1', dtype='category')
df_hmp.columns = idx
df_hmp.index = idx.copy()
df_hmp.columns.name = 'ps_yd_1'

现在,操作分类变量:

df_hmp.columns = df_hmp.columns.add_categories('a')
df_hmp['a'] = df_hmp['$0^{th} - 25^{th}$'] + df_hmp['$25^{th} - 50^{th}$']
# Works like charm

【讨论】:

  • 感谢@DYZ,我收到此错误:*** IndexError: only integers, slices (:), ellipsis (...), numpy.newaxis (None) and integer or boolean arrays are valid indices
  • 只是为了确保我们在同一页面上:您的 pandas 版本是什么?
  • 我的熊猫版本是0.22
  • 我有 0.23.4,差别不大。我更改了答案以使其独立并尽可能接近您的示例。执行的时候还会报错吗?
猜你喜欢
  • 1970-01-01
  • 2015-05-29
  • 1970-01-01
  • 2019-12-27
  • 1970-01-01
  • 2016-09-17
  • 2020-04-30
  • 2021-07-29
  • 1970-01-01
相关资源
最近更新 更多