Python 熊猫:将行与条件合并
我有一个熊猫数据框,下一列是“a”、“B”、“C”、“D”。我想合并具有以下条件的数据帧行- 如果我的数据帧被称为df:Python 熊猫:将行与条件合并,python,pandas,Python,Pandas,我有一个熊猫数据框,下一列是“a”、“B”、“C”、“D”。我想合并具有以下条件的数据帧行- 如果我的数据帧被称为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
(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
或
我尝试了以下非常缓慢的代码:
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
是否有办法仅使用内置功能来完成此任务?先使用,然后使用:
如果无法更改原始值:
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
你好请花点时间阅读这篇文章,以及如何提供答案,并相应地修改你的问题。这些提示可能也很有用。您好,谢谢您的评论。我已经编辑了这个问题,并添加了一个可以复制粘贴到解释器的示例。现在问题清楚了吗?如果没有,请告诉我
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