python - 在 pandas apply 方法中,根据条件复制行
问题描述
这是我的df的一个例子:
pd.DataFrame([["1", "2"], ["1", "2"], ["3", "other_value"]],
columns=["a", "b"])
a b
0 1 2
1 1 2
2 3 other_value
我想达到这个:
pd.DataFrame([["1", "2"], ["1", "2"], ["3", "other_value"], ["3", "row_duplicated_with_edits_in_this_column"]],
columns=["a", "b"])
a b
0 1 2
1 1 2
2 3 other_value
3 3 row_duplicated_with_edits_in_this_column
规则是使用 apply 方法,进行一些检查(为了保持示例简单,我不包括这些检查),但在某些条件下,对于 apply 函数中的某些行,复制该行,对该行进行编辑并在 df 中插入两行。
所以像:
def f(row):
if condition:
row["a"] = 3
elif condition:
row["a"] = 4
elif condition:
row_duplicated = row.copy()
row_duplicated["a"] = 5 # I need also this row to be included in the df
return row
df.apply(f, axis=1)
我不想将重复的行存储在我班级的某个地方并在最后添加它们。我想即时进行。
我见过这个pandas: apply function to DataFrame 可以返回多行,但我不确定 groupby 是否可以在这里帮助我。
谢谢
解决方案
这是df.iterrows
在列表推导中使用的一种方法。您需要将行附加到循环中,然后进行连接。
def func(row):
if row['a'] == "3":
row2 = row.copy()
# make edits to row2
return pd.concat([row, row2], axis=1)
return row
pd.concat([func(row) for _, row in df.iterrows()], ignore_index=True, axis=1).T
a b
0 1 2
1 1 2
2 3 other_value
3 3 other_value
我发现在我的情况下最好没有,ignore_index=True
因为我后来合并了 2 个 dfs。
推荐阅读
- django - Django 模型管理员导入导出数据
- excel - HLOOKUP 替代方案,无需更改表或添加行?
- r - 将具有匹配和不匹配数字的行与附加列关联相结合
- angular - PrimeNG 对话动画
- django - Django generic.ListView:不显示没有指定选项的问题
- c - 如何将 C 代码(或 32 位 dll 文件)编译成 64 位 dll 文件?
- javascript - 使用 Promises 等待 useState 钩子递增计数器
- python - 使用 Python 对目录中的文件进行计数
- c# - 从属性类型中获取属性名称
- python - 如何自动添加基类?