[英]Pandas groupby on list of lists with atleast one element common
I am analyzing a CSV file with names corresponding to their mobile numbers list.我正在分析一个 CSV 文件,其名称与其手机号码列表相对应。
Now, I wish to group by this dataset over 'phone_number' where at least one of the numbers in the list matches with others.现在,我希望通过“phone_number”按此数据集进行分组,其中列表中至少有一个数字与其他数字匹配。
For example,** if Dr. ABC has phone_number=['1234','3456','7890'] in one of the samples & Dr. ABC has phone number=['7676','1234','8765'] in other sample, these rows should be aggregated together as '1234' is common.
例如,** 如果 Dr. ABC 在其中一个样本中有 phone_number=['1234','3456','7890'] 并且 Dr. ABC 的电话号码=['7676','1234','8765' ] 在其他示例中,这些行应聚合在一起,因为“1234”很常见。 Though rows without any match should also be retained
虽然没有任何匹配的行也应该保留
The required output is list of rx_id after grouping over phone_number like this.Can this be done using pandas groupby()?所需的 output 是像这样通过 phone_number 分组后的 rx_id 列表。可以使用 pandas groupby() 来完成吗? or some other trick.
或其他一些技巧。 Thanks for the help!!
谢谢您的帮助!!
IIUC you can use explode
and duplicated
: IIUC 你可以使用
explode
和duplicated
:
df = pd.DataFrame({"doctor_name":["Dr. ABC","Dr. ABC", "Dr. Who","Dr. Strange"],
"phone_number":[['1234','3456','7890'],['7676','1234','8765'], np.NaN, ["8697059406"]]})
df = df.explode("phone_number")
s = df["doctor_name"].value_counts()
print (df[df.duplicated("phone_number")|df["doctor_name"].isin(s[s.eq(1)].index)]) #add .groupby("doctor_name").agg(list) if you want them back into a list
doctor_name phone_number
1 Dr. ABC 1234
2 Dr. Who NaN
3 Dr. Strange 8697059406
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.