如何从同一列的值创建多个列?

时间:2019-04-02 21:58:23

标签: python-3.x pandas dataframe merge multiple-columns

我有一个DataFrame,并且我想基于o同一列的值创建新列,并且在每列中我希望这些值成为 Plate的重复总数

所以我有这个DataFrame:

   Val_Tra.Head():

                             Plate                          EURO    
   Timestamp                            
   2013-11-01 00:00:00               NaN                    NaN
   2013-11-01 01:00:00  dcc2f657e897ffef752003469c688381    0.0 
   2013-11-01 02:00:00  a5ac0c2f48ea80707621e530780139ad    6.0 

因此,我有一个 EURO 列,如下所示:

   Veh_Tra.EURO.value_counts():

   5    1590144
   6     745865
   4     625512
   0     440834
   3     243800
   2      40664
   7      14207
   1       4301 

这是我想要的输出:

                                       Plate               EURO_1    EURO_2    EURO_3    EURO_4    EURO_5    EURO_6   EURO_7    
   Timestamp                            
   2013-11-01 00:00:00               NaN                    NaN      NaN        NaN       NaN        NaN        NaN     NaN
   2013-11-01 01:00:00  dcc2f657e897ffef752003469c688381    1.0      NaN        NaN        NaN       NaN        NaN     NaN 
   2013-11-01 02:00:00  a5ac0c2f48ea80707621e530780139ad    NaN      NaN        1.0        NaN       NaN        NaN     NaN

所以,基本上,我想要的是每次 Plate 值在特定类型的 Euro < / em>

感谢您的任何建议,谢谢。

1 个答案:

答案 0 :(得分:0)

这更像是get_dummies问题

s=df.dropna().EURO.astype(int).astype(str).str.get_dummies().add_prefix('EURO')
df=pd.concat([df,s],axis=1,sort=True)
df
Out[259]: 
                                               Plate  EURO  EURO0  EURO6
2013-11-0100:00:00                               NaN   NaN    NaN    NaN
2013-11-0101:00:00  dcc2f657e897ffef752003469c688381   0.0    1.0    0.0
2013-11-0102:00:00  a5ac0c2f48ea80707621e530780139ad   6.0    0.0    1.0