Python 创建一列,显示其他两列的最大重复对数
我有两列的列表长度相等,但每行两个列表的长度可能不同。我想创建第3列,这是对应于通过在第1列和第2列之间按索引配对数字而创建的最大重复数的数字。例如:Python 创建一列,显示其他两列的最大重复对数,python,pandas,Python,Pandas,我有两列的列表长度相等,但每行两个列表的长度可能不同。我想创建第3列,这是对应于通过在第1列和第2列之间按索引配对数字而创建的最大重复数的数字。例如: df= col 1 col 2 col 3 ["c","c"] ["d", "d"] 2 // ("c","d
df=
col 1 col 2 col 3
["c","c"] ["d", "d"] 2 // ("c","d") is repeated twice
["a","b","c","a"] ["f","e","e","f"] 2 //("a","f") is repeated twice while ("b","e") and ("c","e") are only repeated once
["a","b","g"] ["f","e","f"] 1 //("a","f"), ("b","e"), and ("g","f") are repeated once
到目前为止,我所尝试的:
到目前为止,我的方法是首先创建一个包含元组列表的新列。以我的示例中的第一行为例,我想创建[(“c”,“d”),(“c”,“d”)],并对每一列重复此操作。然后我计划应用计数器(df[“col 3”])。最常见的(1)[0][1]
来获得最大数量的重复对
要创建包含元组列表的列,我尝试了:
df[“col 3”]=list(zip(df[“col 1”]、df[“col 2”])
但这似乎返回([“c”、“c”]、[“d”、“d”]),使用第一行作为示例,而不是[(“c”、“d”)、(“c”、“d”)]
任何帮助都将不胜感激 尝试使用
计数器应用:
df['col 3'] = df.apply(lambda x: np.max(Counter(zip(x['a'], x['b'])).values()), axis=1)
您也可以尝试使用列表理解和numpy:
df['col3'] = [np.max(np.unique(tuple(zip(*entry)),
axis=0,
return_counts=True)[-1])
for entry in zip(df.col1, df.col2)
]