我有一个数据框,其列标题名为 Transportation,其中一些值为 Car、Bus、Ship 或 Nan(用于缺失值)。我打算做的是提取 Transportation 中的所有唯一值(例如,id 为 3 的人和 id 为 6 的人可能有汽车运输),然后将它们放入新的列标题中。
那么,如果id 3 的交通工具是Car,那么Car header 下的行值为1,其他header 下的行值为0。对于 Nan,所有新生成的 header 下的值为 0。
最佳答案
最简单和最快的方法是使用 pandas get_dummies
例子:
考虑这个 DataFrame df
:
Transportation
0 car
1 bus
2 plane
3 NaN
如果你执行这个:
new_df = pd.get_dummies(df,prefix='',prefix_sep='')
print(new_df)
你得到的输出:
bus car plane
0 0 1 0
1 1 0 0
2 0 0 1
3 0 0 0
我相信这就是您要找的。p>
关于python - 将数据框中字符串列的唯一值转换为值为 0 或 1 的新多 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44867639/