2
votes

Créer une nouvelle colonne basée sur une chaîne

J'ai un bloc de données, je souhaite créer une colonne basée sur la chaîne de column1_sport.

column1_sport    column2_type
baseball         ball
basketball       ball
tennis           other 
boxing           box              
golf             other

Les données contiennent:

column1_sport
baseball
basketball
tennis
boxing
golf

Je veux rechercher certaines chaînes ("boule" ou "boîte") et créer une nouvelle colonne en fonction de si la colonne contient ce mot. Si le dataframe ne contient pas ce mot, ajoutez "autre". Voir ci-dessous.

import pandas as pd

df = pd.read_csv('C:/Users/test/dataframe.csv', encoding  = 'iso-8859-1')


0 commentaires

3 Réponses :


0
votes

Vous pouvez utiliser un np imbriqué où

cond1 = df.column1_sport.str.contains('ball')
cond2 = df.column1_sport.str.contains('box')
df['column2_type'] = np.where(cond1, 'ball', np.where(cond2, 'box', 'other') )

    column1_sport   column2_type
0   baseball        ball
1   basketball      ball
2   tennis          other
3   boxing          box
4   golf            other


1 commentaires

@ nia4life, optez pour le np.select de jpp pour plus de conditions



1
votes
def func(a):
    if "ball" in a.lower():
        return "ball"
    elif "box" in a.lower():
        return "box"
    else:
        return "Other"

df["column2_type"] = df.column1_sport.apply(lambda x: func(x))

0 commentaires

2
votes

Pour plusieurs conditions, je suggère np.select . Par exemple:

values = ['ball', 'box']
conditions = list(map(df['column1_sport'].str.contains, values))

df['column2_type'] = np.select(conditions, values, 'other')

print(df)

#   column1_sport column2_type
# 0      baseball         ball
# 1    basketball         ball
# 2        tennis        other
# 3        boxing          box
# 4          golf        other


0 commentaires