簡體   English   中英

合並Pandas Dataframe中的列

[英]Merge Columns in Pandas Dataframe

我有一個包含三列的數據框

Col1    Col2    Col3  Col4  Col 5
---------------------------------
Apple   None    192    abc   None
Banana  Banana  89     None  bcd
None    Cake    892    aaa   aaa

我想要組合兩個列,即Col1和Col2以及col1和col5如果一個列中沒有,而另一個列有值,則使用該值,如果兩個值都有值,則使用該值。
是否可以合並這樣的列。

Col1    Col3     Col4
----------------------
Apple   192      abc
Banana  89       bcd
Cake    892      aaa

使用(如果None是首先用np.nan替換的字符串: df=df.replace('None',np.nan) ):

df_new=df.ffill().bfill()[['Col1','Col3']]
print(df_new)

     Col1  Col3
0   Apple   192
1  Banana    89
2  Banana   892

根據更新:

df.bfill(axis=1)[['Col1','Col3','Col4']]

     Col1 Col3 Col4
0   Apple  192  abc
1  Banana   89  bcd
2    Cake  892  aaa

創建映射dict中,做groupbyfirst

d={'Col1':'Col1','Col2':'Col1','Col3':'Col3','Col4':'Col4','Col5':'Col4'}
Yourdf=df.mask(df=='None').groupby(d,axis=1).first()
Out[88]: 
     Col1  Col3 Col4
0   Apple   192  abc
1  Banana    89  bcd
2    Cake   892  aaa

暫無
暫無

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

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