Python 获取一个df列中的哪个元素对于另一个df列中的每个单独元素最频繁出现(各种单独字符串的列表)
我的pandas数据框中有一个名为“tags”的列,它是多个字符串的列表Python 获取一个df列中的哪个元素对于另一个df列中的每个单独元素最频繁出现(各种单独字符串的列表),python,pandas,dataframe,associations,Python,Pandas,Dataframe,Associations,我的pandas数据框中有一个名为“tags”的列,它是多个字符串的列表 [abc, 123, xyz] [456, 123] [abc, 123, xyz] 我还有另一个列tech,每个列都有一个字符串 win mac win 请让我知道是否有一种方法可以让我获得标签中每个元素在技术中出现最频繁的元素。 例如,与其他技术相比,“abc”最常与“win”联系在一起。因此,输出应该如下所示: abc win 123 win xyz win 456 mac IIUC,您可以分解标记列,并使用交
[abc, 123, xyz]
[456, 123]
[abc, 123, xyz]
我还有另一个列tech,每个列都有一个字符串
win
mac
win
请让我知道是否有一种方法可以让我获得标签中每个元素在技术中出现最频繁的元素。
例如,与其他技术相比,“abc”最常与“win”联系在一起。因此,输出应该如下所示:
abc win
123 win
xyz win
456 mac
IIUC,您可以
分解标记列,并使用交叉表和idxmax
:
输入:
d = {'Tags':[['abc', 123, 'xyz'],[456, 123],['abc', 123, 'xyz']],
'tech':['win','mac','win']}
df = pd.DataFrame(d)
print(df)
Tags tech
0 [abc, 123, xyz] win
1 [456, 123] mac
2 [abc, 123, xyz] win
解决方案:
m = df.explode('Tags')
out = pd.crosstab(m['Tags'],m['tech']).idxmax(1)
Tags
123 win
456 mac
abc win
xyz win
dtype: object
你好,我建议如下:
import pandas as pd
# I reproduce your example
df = pd.DataFrame({"tags": [["abc", "123", "xyz"], ["456", "123"], ["abc", "123", "xyz"]],
"tech": ["win", "mac", "win"]})
# I use explode to have one row per tag
df = df.explode(column="tags")
# then I set index for tags
df = df.set_index("tags").sort_index()
# And then I take the most frequent value by defining a mode function
def mode(x):
'''
Returns mode
'''
return x.value_counts().index[0]
res = df.groupby(level=0).agg(mode)
我明白了
tech
tags
123 win
456 mac
abc win
xyz win
如果还需要与标记关联的频率:
import pandas as pd
from collections import Counter
df = pd.DataFrame({'tech':['win', 'mac', 'win'],
'tags':[['abc', 123, 'xyz'], [456, 123], ['abc', 234, 'xyz']]})
df = df.groupby('tech').sum() # concatenate by tech the lists
df['freq'] = [Counter(el) for el in df['tags']] # convert each list to a dict of frequency
final_df = pd.DataFrame()
# explode the column of dicts
for row in df.iterrows():
tech = row[0] # get the value in the metric column
for key, value in row[1][1].items():
tmp_df = pd.DataFrame({
'tech':tech,
'tag': key,
'frequency': value
}, index=[0])
final_df = final_df.append(tmp_df) # append the tmp_df to our final df
final_df = final_df.reset_index(drop=True)
完美的非常感谢你!!我可以按照标记在数据帧中的显示次数对交叉表中标记的顺序进行排序吗?@AnishaAlluru将out
保存为仅交叉表,并从out
变量中删除idxmax
,然后执行out.idxmax(1).reindex(out.max(1).sort\u值(升序=False).index)
,让我知道:)这是一个有趣的方法和有用的。向上投票