python - 熊猫:用条件合并行
问题描述
我有一个带有下一列的 pandas DataFrame - “A”、“B”、“C”、“D”。我想合并具有以下条件的 DataFrame 的行 -
如果我的 DataFrame 被称为 df:
(df.at[i,"A"] == df.at[j, "B"]) and (df.at[j,"A"] == df.at[i,"B"])
例如 -
df = pd.DataFrame([[1,2,10,0.55],[3,4,5,0.3],[2,1,2,0.7]], columns=["A","B","C","D"])
这使 -
In [93]: df
Out[93]:
A B C D
0 1 2 10 0.55
1 3 4 5 0.30
2 2 1 2 0.70
在上面的示例中,第 0 行和第 2 行具有条件。我确定最多可以有 2 行与此条件相对应。对于具有这种情况的行,我想对“C”值求和,平均“D”并删除冗余行。在上面的例子中,我想得到 -
In [95]: result
Out[95]:
A B C D
0 1 2 12 0.625
1 3 4 5 0.300
或者
In [95]: result
Out[95]:
A B C D
0 2 1 12 0.625
1 3 4 5 0.300
我尝试了以下非常慢的代码:
def remove_dups(path_to_df: str):
df = pd.read_csv(path_to_df)
for i in range(len(df)):
a = df.at[i, "A"]
b = df.at[i, "B"]
same_row = df[(df["A"] == b) & (df["B"] == a)]
if same_row.empty:
continue
c = df.at[i, "C"]
d = df.at[i, "D"]
df.drop(i, inplace=True)
new_ind = same_row.index[0]
df.at[new_ind, "C"] += c
df.at[new_ind, "D"] = (df.at[new_ind, "D"] + distance) / 2
return df
有没有办法只使用内置的 Pandas 函数来实现这一点?
解决方案
df[['A','B']] = np.sort(df[['A','B']], axis=1)
df = df.groupby(['A','B'], as_index=False).agg({'C':'sum', 'D':'mean'})
print (df)
A B C D
0 1 2 12 0.625
1 3 4 5 0.300
如果无法更改原始值:
arr = np.sort(df[['A','B']], axis=1)
df = (df.groupby([arr[:, 0],arr[:, 1]])
.agg({'C':'sum', 'D':'mean'})
.rename_axis(('A','B'))
.reset_index())
print (df)
A B C D
0 1 2 12 0.625
1 3 4 5 0.300
推荐阅读
- hadoop - 如何运行hdp3.1?
- signal-processing - MPT1327 FSK 时钟和数据恢复
- javascript - VuetifyJS 使用 Google Places API 自动完成的高级插槽
- python - 有条件的向后循环
- php - Why my images do not appears in a modal? Codeigniter
- python - 寻找百分比标记
- python - 了解字典抽认卡游戏错误
- sql - 对 Google bigquery 中的非分区数据进行运行计数
- angular - 是否可以使用 ng serve 在 Angular 8 项目中使用 Ionic 4?
- bitbucket-server - 将存储库批量导入本地 bitbucket 安装