首页 > 解决方案 > 清理两列,然后合并为一个值

问题描述

我正在尝试将两列合并为一个,但首先我必须清理它们。我有的:

Index |   Col1   | Col2
  1   | 1 in     |  1.0
  2   | 2 inches | 2.001
  3   |   NA     |   NA

我想要的是:

Index | Merged
1     |  1   
2     |  2
3     |

对于 Col2,我必须掩盖 NA 值以四舍五入。

na_mask = df['Col2'].notnull()
df.loc[na_mask, 'Col2'] = power.loc[na_mask, 'Col2'].astype(float).round(0).astype(int)

对于 Col1,我已经能够删除 col 中的字符,但是当我尝试将其转换为 Int 时出现错误

df['Col1']=df['Col2'].apply(lambda measure: re.sub(r'[a-z]|[A-z]|\"','',str(measure))).astype(int)

最后我加入了这两列,但如果有更简单的方法,请告诉我:

df[['Col1','Col2']].apply(lambda x: ",".join(set([str(i) for i in x if pd.notnull(i)])), axis=1)

标签: pythonpandasjoinmerge

解决方案


推荐阅读