如何在Pandas Groupby中合并连接的字符串

时间:2019-05-02 15:04:18

标签: python pandas pandas-groupby

我试图弄清楚如何计算给定的2个字符串组合,而不管哪个字符串是第一/第二。

这是我的代码:

import pandas as pd

mylist = [[('Smith JR', 'Kim YY'), ('Smith JR', 'Ron AA'), ('Kim YY', 'Ron AA')],
          [('Kim YY', 'Smith JR')], [('Smith JR', 'Ron AA')]]

flat_list = [item for sublist in mylist for item in sublist]

df = pd.DataFrame(flat_list, columns=["From", "To"])
df_graph = df.groupby(["From", "To"]).size().reset_index()
df_graph.columns = ["From", "To", "Count"]

print(df_graph)

给出:

       From        To  Count
0    Kim YY    Ron AA      1
1    Kim YY    Smith JR    1
2  Smith JR    Kim YY      1
3  Smith JR    Ron AA      2

但是由于Kim YY Smith JR和Smith JR Kim YY在我希望给予的两个人之间建立了联系:

       From        To  Count
0    Kim YY    Ron AA      1
1    Kim YY    Smith JR    2
2  Smith JR    Ron AA      2

我已经看到了许多解决方案,它们可以删除重复的行,但是并没有按照我的期望合并每行的计数。我似乎无法弄清楚如何结合

1    Kim YY    Smith JR    1
2  Smith JR    Kim YY      1

行仅保留Kim YY-Smith JR行且Count为2。此外,在我的实际数据中,给定行的计数可以大于1。

2 个答案:

答案 0 :(得分:5)

将两列排序在一起,然后再添加到数据框中,以确保一对将仅以特定顺序出现。然后才应用您的计数方法。使用link中的方法进行排序:

import pandas as pd
import networkx as nx

mylist = [[('Smith JR','Kim YY'),('Smith JR','Ron AA'),('Kim YY','Ron AA')],[('Kim YY','Smith JR')],[('Smith JR','Ron AA')]]

flat_list = [item for sublist in mylist for item in sublist]

df = pd.DataFrame(flat_list, columns=["From", "To"])
#create a new dataframe with the value pairs sorted. You can also sort earlier if you prefer.
df = pd.DataFrame(np.sort(df[["From", "To"]]), columns = ["From", "To"])
#now, just apply the groupby.
df_graph = df.groupby(["From", "To"], axis=0).size().reset_index()
#Output:
     From        To  0
0  Kim YY    Ron AA  1
1  Kim YY  Smith JR  2
2  Ron AA  Smith JR  2

答案 1 :(得分:3)

快速'n肮脏

但不要那么脏

pd.value_counts([*map(frozenset, zip(df.From, df.To))])

(Smith JR, Ron AA)    2
(Kim YY, Smith JR)    2
(Kim YY, Ron AA)      1
dtype: int64