Python 基于另一列的一部分创建一个热编码列';s值
我有这种数据帧Python 基于另一列的一部分创建一个热编码列';s值,python,pandas,Python,Pandas,我有这种数据帧 import pandas as pd df = pd.DataFrame({'year': [1894, 1976, 1995, 2001, 1993]}) 当前的数据帧 year 0 1894 1 1976 2 1995 3 2001 4 1993 year 1800s 1900s 2000s 0 1894 1 0 0 1 1976 0 1 0
import pandas as pd
df = pd.DataFrame({'year': [1894, 1976, 1995, 2001, 1993]})
当前的数据帧
year
0 1894
1 1976
2 1995
3 2001
4 1993
year 1800s 1900s 2000s
0 1894 1 0 0
1 1976 0 1 0
2 1995 0 1 0
3 2001 0 0 1
4 1993 0 1 0
如何有效地添加一个热编码列,使数据帧看起来像这样
预期的数据帧
year
0 1894
1 1976
2 1995
3 2001
4 1993
year 1800s 1900s 2000s
0 1894 1 0 0
1 1976 0 1 0
2 1995 0 1 0
3 2001 0 0 1
4 1993 0 1 0
我已经尝试了下面的代码,它工作了。但是我认为有一个更好的解决方案,你能推荐我可以使用什么功能吗?谢谢大家!
代码
df['year'] = df['year'].astype(str)
df['1800s'] = df['year'].apply(lambda x: 1 if x[:2] == '18' else 0)
df['1900s'] = df['year'].apply(lambda x: 1 if x[:2] == '19' else 0)
df['2000s'] = df['year'].apply(lambda x: 1 if x[:2] == '20' else 0)
前两位使用整数除法,列名重命名为,最后一位用于“添加到原始值”:
df = df.join(pd.get_dummies(df['year'] // 100).add_suffix('00s'))
print (df)
year 1800s 1900s 2000s
0 1894 1 0 0
1 1976 0 1 0
2 1995 0 1 0
3 2001 0 0 1
4 1993 0 1 0
print (df['year'] // 100)
0 18
1 19
2 19
3 20
4 19
Name: year, dtype: int64
print (pd.get_dummies(df['year'] // 100).add_suffix('00s'))
1800s 1900s 2000s
0 1 0 0
1 0 1 0
2 0 1 0
3 0 0 1
4 0 1 0