pandas - 当列包含某些文本时,将所有列值连接到 1 列
问题描述
我想创建一个名为“part_1_total”的新列,它将包含字符串 'Part 1' 的列的所有值粘贴在一起(对于下一组包含 'Part 2' 、 Part 3' 等的列也应该这样做...)
有没有快速的方法来做到这一点?
我的尝试:
# Attempt 1 yields 0 as it is to sum up numbers
def calc_total(df,string='Part 1'):
return df.loc[:,[x for x in df.columns if string in x]].sum(axis=1)
# Attempt number 2 pastes the column names into all the cells
asos['part_1_total'] = ''.join(asos.loc[:,[x for x in asos.columns if 'Part 1' in x]])
解决方案
我认为这只是列子集的 str 连接。
import pandas as pd
import numpy as np
df = pd.DataFrame(
{'Part 1 - Body':[np.nan, '100% Other Material'],
'Part 2 - Back':['43% Nickle', '20% Aluminum'],
'Part 1 - Lining':['93% Cotton', '23% Spandex']}
)
df['part_1_total'] = df[[c for c in df.columns if 'Part 1' in c]].apply(
lambda x: x.str.cat(sep=', '), axis=1)
结果数据框:
Part 1 - Body Part 2 - Back Part 1 - Lining part_1_total
0 NaN 43% Nickle 93% Cotton 93% Cotton
1 100% Other Material 20% Aluminum 23% Spandex 100% Other Material, 23% Spandex
您可以通过调整sep
参数来调整您希望如何连接字符串(使用逗号、空格等)。有关在 pandas 中连接字符串列的更多信息,请参阅此答案。您可以使用''.join
in ,apply
但这似乎不适用于 NaN。
推荐阅读
- templates - 如何在图像预览中隐藏暗模式图标
- java - Junit 测试用例在 Eclipse 中通过,但在 Maven 构建期间失败,并且在 json 文件中显示一些编码错误,如比较错误
- javascript - 将输入限制为小数点后 2 位 jquery onchange 事件
- php - 如何为 Amazon AWS 部署设置作曲家标志 --ignore-platform-reqs
- open-liberty - 有没有办法阻止 MPJwt 验证不受保护/允许的端点。使用 Openliberty 服务器
- reactjs - 如何在 React、Typescript 中使用历史记录?
- arrays - 如果拉入 MongoDB 后数组字段为空,则取消设置数组字段
- flutter - 我们如何使用 Get X 处理深度链接以转到应用程序的自定义页面?
- postgresql - timescaleDB 中的 ASC 时间索引
- javascript - Highcharts React:当全屏模式打开时,菜单按钮不会从“查看全屏”变为“退出全屏”