python - Pandas - 从分类列创建 bool 列

标签 python pandas dataframe

我在 Pandas 数据框中有 Place 列,如下所示:

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

我想做以下事情:

is_Berlin   is_Prague   is_Mexico
1           0           0
0           1           0
0           0           1
0           1           0
0           0           1   

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

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

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

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

但我觉得这有点乏味,我相信有很好的 pythonic 方式来处理它。

最佳答案

您可以使用 str.get_dummies如果需要将此新列添加到原始 DataFrame,请使用 concat :

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
df = pd.concat([df, df1], axis=1)
print df
    Place  is_Berlin  is_Mexico  is_Prague
0  Berlin          1          0          0
1  Prague          0          0          1
2  Mexico          0          1          0
3  Prague          0          0          1
4  Mexico          0          1          0

#if there is more columns, you can drop Place column
df = df.drop('Place', axis=1)
print df
   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

关于python - Pandas - 从分类列创建 bool 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36544089/

相关文章:

python - Pandas 更好的排序、分组、求和方法

python - Pandas:在数据框中从长格式变为宽格式

python - 将列表或系列作为一行 append 到 pandas DataFrame?

r - 观星者产生各种 latex 错误

python - 如何在同一个 Pandas DataFrame 中切换列值

python - pip安装成功后的ImportError

python - 通过在 MATLAB/Python 中优化多个变量来减少两个图之间的差异?

python - 如何能够以一定的字符串长度添加字符(Python)?

python - 如何在多个浏览器中运行一个 python webdriver 测试

python - 删除 DataFrame 中的多个空白