簡體   English   中英

get_dummies() 用於多個 Pandas DataFrame

[英]get_dummies() for multiple Pandas DataFrame's

我有一個 DataFrame 列表,我想對一些列進行一次性編碼。 例如,如果:

In[1]:  df1 = pd.DataFrame(np.array([['a', 'a'], ['b', 'b'], ['c', 'c']]), 
                   columns=['col_1', 'col_2'])
        df2 = pd.DataFrame(np.array([['a', 'a'], ['b', 'b'], ['c', 'c']]),
                   columns=['col_1', 'col_2'])

        combined = [df1, df2]
        combined


Out[1]:    col_1  col_2
        0      a      a
        1      b      b
        2      c      c

我目前正在使用以下方法。

In[2]:  for df in combined:
            one_hot = pd.get_dummies(df["col_2"])

            df[one_hot.columns] = one_hot
            df.drop("col_2", axis=1, inplace=True)

        
        df1

Out[2]:      col_1   a   b   c
          0      a   1   0   0
          1      b   0   1   0 
          2      c   0   0   1

我錯過了更簡潔的解決方案嗎?


編輯

一個重要的要求是我需要修改原始數據幀。

我認為您可以將concatkey一起使用,這將添加一個新級別的索引,然后get_dummies

s=pd.concat(combined,keys=range(len(combined)))['col_2'].str.get_dummies()
s['col_1']=pd.concat(combined,keys=range(len(combined)))['col_1'].values

s
Out[20]: 
     a  b  c col_1
0 0  1  0  0     a
  1  0  1  0     b
  2  0  0  1     c
1 0  1  0  0     a
  1  0  1  0     b
  2  0  0  1     c

如果您想將它們保存到不同 dfs 的列表中,您可以groupby並將其保存到dict

d={x:y.reset_index(level=0,drop=True) for x , y in s.groupby(level=0)}
d
Out[16]: 
{0:    a  b  c
 0  1  0  0
 1  0  1  0
 2  0  0  1, 1:    a  b  c
 0  1  0  0
 1  0  1  0
 2  0  0  1}

OP的方法就好了

for df in combined:
    one_hot = pd.get_dummies(df["col_2"])

    df[one_hot.columns] = one_hot
    df.drop("col_2", axis=1, inplace=True)

重新分配給所有名稱

df1, df2 = [df.join(pd.get_dummies(df['col_2'])).drop('col_2', 1) for df in combined]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM