【发布时间】:2019-11-19 18:52:06
【问题描述】:
我的数据:
Rank Platforms Technology
high Windows||Linux Unity
high Linux
low Windows Unreal
low Linux||MacOs GameMakerStudio||Unity||Unreal
low GameMakerStudio
low
我想把它转换成这样的:
Rank platform_Windows platform_linux platform_MacOs technology_unity technology_unreal technology_GameMakerStudio
high 1 0 0 1 0 1
high 0 1 0 0 0 0
low 1 0 0 0 1 0
low 0 1 1 1 1 1
low 0 0 0 0 0 1
low 0 0 0 0 0 0
所以这是一种单热编码。我关注了很多答案:
- How to one-hot-encode from a pandas column containing a list?
- Pandas get_dummies to create one hot with separator = ' ' and with character level separation [duplicate]
- ow to one-hot-encode from a pandas column containing a list?
问题是:
- 没有一个显示如何用
||分隔符分隔我的列表 - 它们都没有显示如何为新列名添加前缀。例如
platform_和technology_。我需要这个来知道新列来自哪个原始列。
我当前的代码是:
df.drop('Platforms', 1).join(
pd.get_dummies(
pd.DataFrame(df.Platforms.str.split("||").tolist()).stack(),
prefix=['platform']
).assum(level=0)
)
df.drop('Technology', 1).join(
pd.get_dummies(
pd.DataFrame(df.Technology.str.split("||").tolist()).stack(),
prefix=['technology']
).assum(level=0)
)
但我得到的错误是:
TypeError: 'float' 类型的对象没有 len()
我已阅读文档pandas.get_dummies 和pandas.Series.str.get_dummies。后者似乎接受自定义分隔符,而前者允许自定义新列前缀...
【问题讨论】:
-
df.Platforms.str.get_dummies()似乎按预期工作。 -
@Quang Hoang 它不允许列名前缀
platform_和technology_ -
别偷懒,直接上链吧:
df.Platforms.str.get_dummies().add_prefix('Platform_'):D -
哦,再看一遍,它会产生一个
None列。之后可能会被丢弃。 -
@QuangHoang 你能发布一个完整的工作代码作为答案吗?谢谢
标签: python python-3.x pandas dataframe one-hot-encoding