gpt4 book ai didi

python - 将 pandas DataFrame 列拆分为 OneHot/Binary 列

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:44 26 4
gpt4 key购买 nike

我有一个 DataFrame,我正在为 SciKit Learn PCA 格式化,看起来像这样:

datetime |  mood |  activities |  notes

8/27/2017 | "good" | ["friends", "party", "gaming"] | NaN

8/28/2017 | "meh" | ["work", "friends", "good food"] | "Stuff stuff"

8/29/2017 | "bad" | ["work", "travel"] | "Fell off my bike"

...等等

我想把它改成这样,我认为这对 ML 工作会更好:

datetime |  mood |  friends | party | gaming | work | good food | travel |  notes

8/27/2017 | "good" | True | True | True | False | False | False | NaN

8/28/2017 | "meh" | True | False | False | True | True | False | "Stuff stuff"

8/29.2017 | "bad" | False | False | False | False | True | False | True | "Fell off my bike"

我已经尝试过概述的方法 here ,这只是给了我所有事件的左对齐矩阵。这些列没有意义。如果我尝试将 columns 传递给 DataFrame 构造函数,我会得到一个错误“26 columns passed, passed data had 9 columns. I believe that's because even though I have 26 discrete事件,我在一天内同时完成的最多是 9 个。如果在特定行中找不到该列,有没有办法让它填充 0/False?谢谢。

最佳答案

你可以简单地使用get_dummies

让我们假设这个数据框:

df = pd.DataFrame({'datetime':pd.date_range('2017-08-27', '2017-08-29'),
'mood':['good','meh','bad'],'activities':[['friends','party','gaming'],
["work", "friends", "good food"],
["work", "travel"]],
'notes':[np.nan, 'stuff stuff','fell off my bike']})
df.set_index(['datetime'], inplace=True)

mood activities notes
datetime
2017-08-27 good [friends, party, gaming] NaN
2017-08-28 meh [work, friends, good food] stuff stuff
2017-08-29 bad [work, travel] fell off my bike

只是 concatget_dummies:

df2 = pd.concat([df[['mood','notes']], pd.get_dummies(df['activities'].apply(pd.Series),
prefix='activity')], axis=1)


mood notes activity_friends activity_work activity_friends activity_party activity_travel activity_gaming activity_good food
datetime
2017-08-27 good NaN 1 0 0 1 0 1 0
2017-08-28 meh stuff stuff 0 1 1 0 0 0 1
2017-08-29 bad fell off my bike 0 1 0 0 1 0 0

如果您想使用 loc,您可以将它们更改为 bool 值:

df2.loc[:,df2.columns[2:]] = df2.loc[:,df2.columns[2:]].astype(bool)

关于python - 将 pandas DataFrame 列拆分为 OneHot/Binary 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53825184/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com