繁体   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