python - Pandas 按值分组并合并行
问题描述
我有一个 DataFrame,我想合并包含相同值的行
toy = [
[10, 11],
[21, 22],
[11, 15],
[22, 23],
[15, 33]
]
toy = pd.DataFrame(toy, columns = ['ID1', 'ID2'])
ID1 ID2
0 10 11
1 21 22
2 11 15
3 22 23
4 15 33
我希望之后得到的是
0 1 2 3
0 10 11 15 33.0
1 21 22 23 NaN
因此合并其中包含任何相同值的行。
我的解决方案超级不优雅,我正在寻找正确的方法来做到这一点......递归?通过...分组?唔..
#### Feel Free to NOT read this... ###
for k in range(100):
print(k)
merge_df = []
merged_indices = []
for i, row in toy.iterrows():
if i in merged_indices:
continue
cp = toy.copy()
merge_rows = cp[cp.isin(row.values)].dropna(how="all")
merged_indices = merged_indices + list(merge_rows.index)
merge_rows = np.array(toy.iloc[merge_rows.index]).flatten()
merge_rows = np.unique(merge_rows)
merge_df.append(merge_rows)
if toy.shape[0] == len(merge_df):
break
toy = pd.DataFrame(merge_df).copy()
解决方案
听起来像网络问题,所以我使用networkx
import networkx as nx
G=nx.from_pandas_edgelist(toy, 'ID1', 'ID2')
l=list(nx.connected_components(G))
newdf=pd.DataFrame(l)
newdf
Out[896]:
0 1 2 3
0 33 10 11 15.0
1 21 22 23 NaN
推荐阅读
- java - 对 Hashtable JSP 的每个元素使用子字符串
- r - OS-Version 和 R-Version 稳定的 Docker 镜像
- excel - Excel 宏调用不适用于计时器,但适用于另一个宏
- excel - 当指定的字符串出现在行中时,VBA Excel将数据从一个工作簿复制到另一个工作簿
- list - Linq 从字符串列表中获取元素以及该列表中字符的位置
- vba - 我可以在 Access 中使用 VBA 来确定用户是否打开了多个数据库实例?
- google-chrome - HTTP 302 上的不同浏览器行为
- java - PoolingHttpClientConnectionManager 的实现
- react-native - 反应本机导航 - 状态更改时不会重新渲染材质顶部选项卡
- javascript - 一旦永远计算,我们如何存储几个变量的实例?