【问题标题】:How to create a pandas column with words from another column, contained in a list如何使用列表中包含的另一列中的单词创建熊猫列
【发布时间】:2021-12-17 18:22:45
【问题描述】:

我想从 pandas 列的字符串中删除列表中指定的单词,并用它们构建另一个列。 我有这个例子的灵感来自问题python pandas if column string contains word flag

listing  = ['test', 'big']
df = pd.DataFrame({'Title':['small test','huge Test', 'big','nothing', np.nan, 'a', 'b']})
df['Test_Flag'] = np.where(df['Title'].str.contains('|'.join(listing), case=False, 
na=False), 'T', '')
print (df)
        Title         Test_Flag
0  small test         T
1  huge Test          T
2  big                T
3  nothing
4   NaN          
5     a
6     b

但是,如果我想在列表中找到实际单词而不是“T”怎么办? 所以,有一个结果:

        Title       Test_Flag
0  small test       test
1  huge Test        test
2  big              big
3  nothing
4   NaN          
5     a
6     b

【问题讨论】:

  • 如果有帮助,请接受我的回答,如果没有解决您的问题,请提供更多信息:)
  • 太好了!我实际上已经意识到,在某些情况下,我可能有像“smalltest”这样的数据,并且仍然想在其中捕获“test”。我将如何添加此功能??
  • 我编辑了我的答案以包含这个

标签: python pandas list contains


【解决方案1】:

.apply 方法与自定义函数一起使用应该可以满足您的需求

import pandas as pd
import numpy as np

# Define the listing list with the words you want to extract
listing  = ['test', 'big']
# Define the DataFrame
df = pd.DataFrame({'Title':['small test','huge Test', 'big','nothing', np.nan, 'a', 'b']})

# Define the function which takes a string and a list of words to extract as inputs
def listing_splitter(text, listing):
    # Try except to handle np.nans in input
    try:
        # Extract the list of flags
        flags = [l for l in listing if l in text.lower()]
        # If any flags were extracted then return the list
        if flags:
            return flags
        # Otherwise return np.nan
        else:
            return np.nan
    except AttributeError:
        return np.nan

# Apply the function to the column
df['Test_Flag'] = df['Title'].apply(lambda x: listing_splitter(x, listing))
df

输出:

    Title       Test_Flag
0   small test  ['test']
1   huge Test   ['test']
2   big         ['big']
3   nothing     NaN
4   NaN         NaN
5   a           NaN
6   b           NaN
7   smalltest   ['test']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-24
    • 2021-12-17
    • 2023-02-05
    • 2021-09-29
    • 1970-01-01
    • 2015-05-28
    • 2021-09-20
    • 2019-10-05
    相关资源
    最近更新 更多