python - 如果列包含列表的子字符串,则替换列的值

标签 python pandas dataframe

所以我有一个 pandas 数据框,如果字符串包含 thyat 元素(子字符串),我尝试将每个值(在我的例子中是一个字符串)替换为列表的元素。为了澄清一下,我有一个简单的数据框:

data = {'column': ['I have a dog', 'and I have two cats', 'I have nothing', 'I like pandas', " "]}
df = pd.DataFrame(data)
list = ['dog', 'cat', 'panda']

所需的输出如下所示:

data = {'column': ['dog', 'cat', 'I have nothing', 'pandas', " "]}
df = pd.DataFrame(data)

我可以执行以下操作:

df.loc[df['column'].str.contains("dog"), "column"]= "dog"

上面的代码行也适用于猫和 Pandas 。但问题是,如果子字符串列表很长,这将需要很多行代码。有没有更简单的方法来做到这一点?因此,对于每个记录,它需要检查它是否包含列表中的任何元素,然后用该元素替换该值。

最佳答案

这里使用循环更简单:

L = ['dog', 'cat', 'panda']
    
for x in L:
    df.loc[df['column'].str.contains(x), "column"]= x
print (df)
           column
0             dog
1             cat
2  I have nothing
3           panda
4                

或者使用Series.str.extractSeries.fillna按原始数据:

df['column'] =  (df['column'].str.extract(f'({"|".join(L)})', expand=False)
                             .fillna(df['column']))
print (df)
           column
0             dog
1             cat
2  I have nothing
3           panda
4                

关于python - 如果列包含列表的子字符串,则替换列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70379410/

相关文章:

python - 如果给出值,则忽略 optparse

python - 如何在 Tensorflow 2.0 数据集中动态更改批量大小?

python Pandas : Assign Last Value of DataFrame Group to All Entries of That Group

python - Pandas:使用 apply 创建 2 个新列

python - 通过 pip 安装本地轮时 ValueError "Expected version spec"

python - 在没有麦克风小部件的情况下使用 OSX 语音识别

python - 根据条件融化数据框

python - 使用 pandas 数据框中的两行来选择另一个数据框中的位置

R - 将三个数据框的列表合并为单个数据框,第一列有 ID,接下来的三列显示值

python - 读取 pandas 中除最后一行 CSV 文件以外的所有内容