[英]Recode catagorical variable as integers in Pandas
我問過R這個問題,但現在正嘗試在熊貓中做。 我正在嘗試使用pandas將類別變量重新編碼為整數。 鑒於:
group
005j
005j
0k16
0fff
0fff
我想得到一系列表示相同分組的遞增整數:
group intCode
005j 1
005j 1
0k16 2
0fff 3
0fff 3
In [10]: df['intCode'] = pd.Categorical.from_array(df.group).labels
In [11]: df
Out[11]:
group intCode
0 005j 0
1 005j 0
2 0k16 2
3 0fff 1
4 0fff 1
只需提供@herrfz答案的更新版本。 Categorical.from_array
和labels
已被棄用。
df['intCode'] = pd.Categorical(df.group).codes
為我運行Python 3.6.9工作
您可以獲得獨特的價值
>>> df = pd.read_clipboard()
>>> groups = df['group'].unique()
索引他們
>>> groups = pd.DataFrame(groups, columns=['group']).reset_index()
然后合並回去(將1從1開始而不是從0開始):
>>> groups['index'] += 1
>>> df.merge(groups)
group index
0 005j 1
1 005j 1
2 0k16 2
3 0fff 3
4 0fff 3
[5 rows x 2 columns]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.