Pandas从分类列创建布尔列

2024-10-06 11:30:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Pandas dataframe中有一个列Place,如下所示:

**Place**
Berlin
Prague
Mexico
Prague
Mexico
...

我想做以下事情:

^{pr2}$

我知道我可以单独创建列:

df['is_Berlin'] = df['Place']
df['is_Prague'] = df['Place']
df['is_Mexico'] = df['Place']

然后为每个列创建一个字典并应用map函数。在

#Example just for is_Berlin column
d = {'Berlin': 1,'Prague': 0,'Mexico': 0} 
df['is_Berlin'] = df['is_Berlin'].map(d)

但我觉得这有点乏味,我相信有一种很好的Python式的方法。在


Tags: 函数mapdataframepandasdf字典isexample
1条回答
网友
1楼 · 发布于 2024-10-06 11:30:24

您可以使用^{},如果需要将此新列添加到原始的DataFrame,请使用^{}

df1 = df.Place.str.get_dummies()
print df1
   Berlin  Mexico  Prague
0       1       0       0
1       0       0       1
2       0       1       0
3       0       0       1
4       0       1       0

df1.columns = ['is_' + col for col in df1.columns]
print df1
   is_Berlin  is_Mexico  is_Prague
0          1          0          0
1          0          0          1
2          0          1          0
3          0          0          1
4          0          1          0
^{pr2}$

相关问题 更多 >