基于它所属的组的一个熊猫列的所有排列和组合(All permutations and combinations of a pandas column based on the group it bel

编程入门 行业动态 更新时间:2024-10-25 16:31:04
基于它所属的组的一个熊猫列的所有排列和组合(All permutations and combinations of a pandas column based on the group it belongs to)

我有一个拥有城市名称和所属州的熊猫数据框。 我试图获得每个州的城市名称比较的所有可能组合。

示例数据框:

City State ---------- LosA Cali SanJ Cali SanF Cali Char NC Rale NC

预期答案:

City1 City2 State ---------- LosA SanJ Cali LosA SanF Cali SanJ SanF Cali Char Rale NC

我使用了itertools的组合,它给出了整个组合,但是有没有办法基于状态实现?

I have a pandas dataframe which has city names and the state to which they belong. I am trying to obtain all the possible combinations of city name comparisons for each state.

Example dataframe:

City State ---------- LosA Cali SanJ Cali SanF Cali Char NC Rale NC

Expected Answer:

City1 City2 State ---------- LosA SanJ Cali LosA SanF Cali SanJ SanF Cali Char Rale NC

I have used combinations from itertools which gives the whole combinations, but is there a way to achieve based on the State as well?

最满意答案

使用groupby + itertools.combinations的组合:

from itertools import combinations g = df.groupby('State').apply(lambda x: pd.Series(list(combinations(x.City, 2)))) df = pd.DataFrame(g.apply(list).tolist(), columns=['City1', 'City2']) df['State'] = g.index.get_level_values(0) df City1 City2 State 0 LosA SanJ Cali 1 LosA SanF Cali 2 SanJ SanF Cali 3 Char Rale NC

Use a combination of groupby + itertools.combinations:

from itertools import combinations g = df.groupby('State').apply(lambda x: pd.Series(list(combinations(x.City, 2)))) df = pd.DataFrame(g.apply(list).tolist(), columns=['City1', 'City2']) df['State'] = g.index.get_level_values(0) df City1 City2 State 0 LosA SanJ Cali 1 LosA SanF Cali 2 SanJ SanF Cali 3 Char Rale NC

更多推荐

本文发布于:2023-07-31 22:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1348593.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   熊猫   排列   permutations   combinations

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!