私は愚か者を持っています。データフレーム:
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')
それを修正する方法は?
データフレーム内のすべての列と行には、カテゴリインデックスがあります。別の列を追加する場合は、最初に別の値をカテゴリカルインデックスに追加する必要があります。
まず、データフレームを再作成しましょう。
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
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加