向 Dataframe 中的分类数据添加标签
Add labels to Categorical Data in Dataframe
我正在尝试转换有关婚姻状况的调查数据,如下所示:
df['d11104'].value_counts()
[1] Married 1 250507
[2] Single 2 99131
[4] Divorced 4 32817
[3] Widowed 3 24839
[5] Separated 5 8098
[-1] keine Angabe 2571
Name: d11104, dtype: int64
到目前为止,我做了 df['marstat'] = df['d11104'].cat.codes.astype('category')
,产生了
df['marstat'].value_counts()
1 250507
2 99131
4 32817
3 24839
5 8098
0 2571
Name: marstat, dtype: int64
现在,我想给列marstat
添加标签,这样数值就保持不变,即我想通过条件df['marstat'] == 1
来识别人,同时暂时将标签 ['Married','Single','Divorced','Widowed']
附加到此变量。如何才能做到这一点?
编辑:感谢 jpp 的回答,我只是创建了一个新变量并手动定义了标签:
df['marstat_lb'] = df['marstat'].map({1: 'Married', 2: 'Single', 3: 'Widowed', 4: 'Divorced', 5: 'Separated'})
您可以将结果转换为数据框,并在输出中包含类别代码和名称。
可以通过枚举类别来提取类别映射的字典。下面是最小的例子。
import pandas as pd
df = pd.DataFrame({'A': ['M', 'M', 'S', 'D', 'W', 'M', 'M', 'S',
'S', 'S', 'M', 'W']}, dtype='category')
print(df.A.cat.categories)
# Index(['D', 'M', 'S', 'W'], dtype='object')
res = df.A.cat.codes.value_counts().to_frame('count')
cat_map = dict(enumerate(df.A.cat.categories))
res['A'] = res.index.map(cat_map.get)
print(res)
# count A
# 1 5 M
# 2 4 S
# 3 2 W
# 0 1 D
例如,您可以通过 df['A'] == 'M'
或 df.index == 1
.
访问 "M"
一个更直接的解决方案是使用 apply value_counts
然后为代码添加一个额外的列:
res = df.A.value_counts().to_frame('count').reset_index()
res['code'] = res['index'].cat.codes
index count code
0 M 5 1
1 S 4 2
2 W 2 3
3 D 1 0
我正在尝试转换有关婚姻状况的调查数据,如下所示:
df['d11104'].value_counts()
[1] Married 1 250507
[2] Single 2 99131
[4] Divorced 4 32817
[3] Widowed 3 24839
[5] Separated 5 8098
[-1] keine Angabe 2571
Name: d11104, dtype: int64
到目前为止,我做了 df['marstat'] = df['d11104'].cat.codes.astype('category')
,产生了
df['marstat'].value_counts()
1 250507
2 99131
4 32817
3 24839
5 8098
0 2571
Name: marstat, dtype: int64
现在,我想给列marstat
添加标签,这样数值就保持不变,即我想通过条件df['marstat'] == 1
来识别人,同时暂时将标签 ['Married','Single','Divorced','Widowed']
附加到此变量。如何才能做到这一点?
编辑:感谢 jpp 的回答,我只是创建了一个新变量并手动定义了标签:
df['marstat_lb'] = df['marstat'].map({1: 'Married', 2: 'Single', 3: 'Widowed', 4: 'Divorced', 5: 'Separated'})
您可以将结果转换为数据框,并在输出中包含类别代码和名称。
可以通过枚举类别来提取类别映射的字典。下面是最小的例子。
import pandas as pd
df = pd.DataFrame({'A': ['M', 'M', 'S', 'D', 'W', 'M', 'M', 'S',
'S', 'S', 'M', 'W']}, dtype='category')
print(df.A.cat.categories)
# Index(['D', 'M', 'S', 'W'], dtype='object')
res = df.A.cat.codes.value_counts().to_frame('count')
cat_map = dict(enumerate(df.A.cat.categories))
res['A'] = res.index.map(cat_map.get)
print(res)
# count A
# 1 5 M
# 2 4 S
# 3 2 W
# 0 1 D
例如,您可以通过 df['A'] == 'M'
或 df.index == 1
.
一个更直接的解决方案是使用 apply value_counts
然后为代码添加一个额外的列:
res = df.A.value_counts().to_frame('count').reset_index()
res['code'] = res['index'].cat.codes
index count code
0 M 5 1
1 S 4 2
2 W 2 3
3 D 1 0