从Numpy数组在数据帧中查找子字符串?

2024-05-29 06:05:35 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在一个数组的数据帧中找到子字符串列表,并使用数组值创建一个新列?例如,我开始使用str.contains并键入实际的字符串值(见下文)

import pandas as pd
import numpy as np

#Filepath directory
csv_report = filepath

#Creates dataframe of CSV report
csv_df = pd.read_csv(csv_report)
  
csv_df['animal'] = np.where(csv_df.item_name.str.contains('Condor'), "Condor",
                   np.where(csv_df.item_name.str.contains('Marmot'), "Marmot",
                   np.where(csv_df.item_name.str.contains('Bear'),"Bear",
                   np.where(csv_df.item_name.str.contains('Pika'),"Pika",
                   np.where(csv_df.item_name.str.contains('Rat'),"Rat",
                   np.where(csv_df.item_name.str.contains('Racoon'),"Racoon",
                   np.where(csv_df.item_name.str.contains('Opossum'),"Opossum")))))))

如果字符串值在数组中,我将如何实现上述代码?以下示例:

import pandas as pd
import numpy as np

#Filepath directory
csv_report = filepath

#Creates dataframe of CSV report
csv_df = pd.read_csv(csv_report)

animal_list = np.array(['Condor', 'Marmot','Bear','Pika','Rat','Racoon','Opossum'])

Tags: csv字符串nameimportreportdfasnp
2条回答

有一种比使用apply或几个np.where更好的方法。看看np.select。 这里和另一个答案一样,我们假设每一行只能有一个匹配项

资料

从@Jonathan Leon偷来的

import pandas as pd
import numpy as np
data = ['Condor', 
        'Marmot',
        'Bear',
        'Condor a',
        'Marmotb',
        'Bearxyz']

df = pd.DataFrame(data, columns=["item_name"])

animal_list = ['Condor', 
               'Marmot',
               'Bear',
               'Pika',
               'Rat',
               'Racoon',
               'Opossum']

定义numpy select的条件

cond_list = [df["item_name"].str.contains(animal) 
             for animal in animal_list]

df["animal"] = np.select(cond_list, animal_list)

输出


  item_name  animal
0    Condor  Condor
1    Marmot  Marmot
2      Bear    Bear
3  Condor a  Condor
4   Marmotb  Marmot
5   Bearxyz    Bear

不区分大小写

在这里,您应该使用

cond_list = [df["item_name"].str.lower()\
             .str.contains(animal.lower()) 
             for animal in animal_list]

df["animal"] = np.select(cond_list, animal_list)

我认为有一个更干净的方法来写这个,但它做你想要的。如果您担心区分大小写或全词匹配,则必须根据需要修改此选项。此外,您不需要np.array,只需要一个列表

import io
import pandas as pd

data = '''item_name
Condor
Marmot
Bear
Condor a
Marmotb
Bearxyz
'''
df = pd.read_csv(io.StringIO(data), sep=' \s+', engine='python')
df

animal_list = ['Condor', 'Marmot','Bear','Pika','Rat','Racoon','Opossum']

def find_matches(x):
    for animal in animal_list:
        if animal in x['item_name']:
            return animal

df.apply(lambda x: find_matches(x), axis=1)

0    Condor
1    Marmot
2      Bear
3    Condor
4    Marmot
5      Bear
dtype: object

相关问题 更多 >

    热门问题