首页 > 解决方案 > 如何在 Pandas Dataframe 中合并多个名称相似的列而不丢失数据

问题描述

我正在处理一些杂乱的数据,并且试图弄清楚如何将具有相似信息的多列合并到一列中。例如,我有一个看起来像这样的数据框,我想知道如何将所有三列压缩为一列:

国家------------州 ------ 温度 ------ 温度 ------ 度

美国 -----肯塔基州 --- $76 ------ 76 -------------------- N/A

美国 -----亚利桑那州 ----- 92\n -------- N/A ------------------ N/A

美国 ----- 密歇根州 -- 45 ------------ 45@ ----- 60

标签: pythonpandasdataframedata-cleaning

解决方案


你可以试试这个,然后删除不需要的列:

df['combined'] = df.apply(lambda x: list([x['Temp'],
                                        x['Temperature'],
                                        x['Degrees']]),axis=1) 

如果您希望它们用斜线分隔,您也可以这样做

df.apply(lambda x: x.Temp + ' / ' + x.Temperature + ' / ' + x.Degrees, axis=1)

# or simply

df['combined'] = df.Temp + ' / ' + df.Temperature + ' / ' + df.Degrees

我用 NaN 数据对我的一些数据进行了测试,它与 NaN 一起工作,也许值得一试:

import numpy as np
def combine_with_nan(x):
   try:
      np.isnan(x.Temp)
      Temp = 'NaN'
   except:
      Temp = x.Temp
   try:
      np.isnan(x.Temperature)
      Temperature = 'NaN'
   except:
      Temperature = x.Temperature
   try:
      np.isnan(x.Degrees)
      Degrees = 'NaN'
   except:
      Degrees = x.Degrees
   return Temp + ' / ' + Temperature + ' / ' + Degrees

df.apply(combine_with_nan, axis=1)

推荐阅读