我有一个来自上一个数据帧的ID列表,例如[1、2、3、4、5],还有另一个数据框,说
具有ID和群集的数据框:
如果数据帧中有匹配的ID,我想按群集更改所有ID组以使其具有该ID。因此,结果数据框将为
其ID与集群中的第一个数据帧匹配的数据帧
答案 0 :(得分:0)
这对我有用:
import pandas as pd
list_ids = [1, 2, 3, 4, 5]
df = pd.DataFrame({'id': [3, 5, 6, 7, 8], 'cluster': [1, 2, 3, 2, 1]})
true_values = df['cluster'] == list_ids
for num, value in enumerate(true_values):
if not value:
cluster_number = df['cluster'][num]
cluster_id = df['cluster'].where(df['cluster'] == cluster_number)
cluster_id = cluster_id.dropna().index[0]
df['id'][num] = df['id'][cluster_id]
print(df)
输出:
id cluster
0 3 1
1 5 2
2 6 3
3 5 2
4 3 1