python - 如何在 Pandas Dataframe 中合并多个名称相似的列而不丢失数据
问题描述
我正在处理一些杂乱的数据,并且试图弄清楚如何将具有相似信息的多列合并到一列中。例如,我有一个看起来像这样的数据框,我想知道如何将所有三列压缩为一列:
国家------------州 ------ 温度 ------ 温度 ------ 度
美国 -----肯塔基州 --- $76 ------ 76 -------------------- N/A
美国 -----亚利桑那州 ----- 92\n -------- N/A ------------------ N/A
美国 ----- 密歇根州 -- 45 ------------ 45@ ----- 60
解决方案
你可以试试这个,然后删除不需要的列:
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)
推荐阅读
- r - 为什么 group_by 不能在 dplyr 中使用 max(colSums)
- c# - 是否可以禁用 DataGridView 中单个列的交替行?
- angular5 - Obervable.create 未在 angular5 中使用 ngrx 触发
- php - 将 PDF 下载到浏览器
- linux-kernel - 在 Linux 中检查进程的堆栈使用情况
- azure - 如何集成驻留在不同 Azure B2c 租户中的两个 WebApp 以获得单点登录体验?
- javascript - 将数据复制到剪贴板而不选择任何文本
- javascript - 如何复制仅保留当前道具的对象?
- karate - 如何在空手道框架中设置代理
- c# - 除以两位小数并将结果转换为 int