【发布时间】:2019-01-05 00:21:49
【问题描述】:
这是我的 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 that can return multiple rows,但我不确定 groupby 是否可以在这里帮助我。
谢谢
【问题讨论】: