Skip to main content
 首页 » 编程设计

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

2025年05月04日20www_RR

我有一个 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 

只是 concat 和 get_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)