python - 将 CELL 中最常见的元素附加到 pandas 列

标签 python pandas

这与我之前提出的一个问题有关,我发布这个新问题是因为我认为它足够了 unique并持续困难。我有一个以下形式的数据框:

keyword       string                 match

A             "Varied String..."     ['string','string','test','string']
              "Varied String..."     ['string','string']
              "Varied String..."     ['test']
B             "Varied String..."     ['string,'string','test']

这是通过以下代码创建的(由@anky_91编写):

df1.groupby(df2.Type.ffill()).matches.apply(lambda x: ''.join(mode(list(chain.from_iterable(x)))[0]))

我目前的问题是,这会创建一个新的列匹配,这是完全正常的,但是虽然我确实想要该模式,但我只想要最常见的唯一值。因此,我不是用列表模式填充 match 列,而是尝试使其成为该模式中最常见的值,因此:

 keyword           string               match

    A             "Varied String..."    'string'
    B             "Varied String..."    'string'

我尝试这样做:

df = freq_df['matches'].agg(lambda x: x.value_counts().index[0])

返回后,同样的事情没有改变。然后我尝试,

df['matches'].value_counts()

这会返回不准确的计数,所以我不确定这是怎么回事。

请告诉我这是否清楚!

最佳答案

您可以使用 Series.str.extractall() 而不是使用 Series.str.findall() 来检索列表中的匹配项。将每个匹配的单词检索到其自己的行中,这可以使您的任务更轻松(下面使用上一篇文章中的示例数据并从 string 列中删除双引号)。

# list of keywords
keyword_list=['string', 'test'] 

# regex pettern to retrieve only words matched from keywork_list
ptn = r'\b(' + '|'.join(keyword_list) + r')\b'

# get the list of matched words (assume `keyword` is already on index), if not, use the following
# s = df.set_index('keyword').string.str.extractall(ptn).reset_index(level=1, drop=True)[0]
s = df.string.str.extractall(ptn).reset_index(level=1, drop=True)[0]
print(s)
#keyword
#A      test
#A    string
#A      test
#A    string
#A    string
#A    string
#A      test
#A    string
#B      test
#B    string
#B      test
#B    string
#B      test
#Name: 0, dtype: object

接下来,您可以通过 value_counts() 为每个关键字检索顶部项目

s.groupby('keyword').apply(lambda x: x.value_counts().nlargest(1))
#keyword   
#A        string    5
#B        test      3
#Name: 0, dtype: int64

或者只是关键字和字符串而不包含计数:

s.groupby('keyword').apply(lambda x: x.value_counts().idxmax())
#keyword
#A    string
#B      test
#Name: 0, dtype: object

关于python - 将 CELL 中最常见的元素附加到 pandas 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56349094/

相关文章:

python - 数据帧的行总和返回零。 (当只有几行有 N/A 时)

Python Pandas 名称错误 : StringIO is not defined

python - 更改时间戳中的时间

python - Python 对于大型应用程序是否足够好?

python - 在序列化器中创建访问另一个模型属性的新字段

python - 从包含标题和分隔符的文本文件中提取列

python - 更改 pandas datetime64 列的时间组件

python - 如何增加Google Colab单元输出宽度?

python - 如何找到csv文件列的平均值

python - 日期时间变量为空