簡體   English   中英

如果它包含熊貓中的子字符串,則替換整個字符串

[英]Replace whole string if it contains substring in pandas

我想替換所有包含特定子字符串的字符串。 例如,如果我有這個數據框:

import pandas as pd
df = pd.DataFrame({'name': ['Bob', 'Jane', 'Alice'], 
                   'sport': ['tennis', 'football', 'basketball']})

您可以使用str.contains來屏蔽包含'ball'的行,然后使用新值覆蓋:

In [71]:
df.loc[df['sport'].str.contains('ball'), 'sport'] = 'ball sport'
df

Out[71]:
    name       sport
0    Bob      tennis
1   Jane  ball sport
2  Alice  ball sport

為了使它不區分大小寫傳遞`case = False:

df.loc[df['sport'].str.contains('ball', case=False), 'sport'] = 'ball sport'

你可以使用lambda的apply lambda函數的x參數將是'sport'列中的每個值:

df.sport = df.sport.apply(lambda x: 'ball sport' if 'ball' in x else x)

你可以使用str.replace

df.sport.str.replace(r'(^.*ball.*$)', 'ball sport')

0        tennis
1    ball sport
2    ball sport
Name: sport, dtype: object

重新分配

df['sport'] = df.sport.str.replace(r'(^.*ball.*$)', 'ball sport')
df

在此輸入圖像描述

一個不同的str.contains

 df['support'][df.name.str.contains('ball')] = 'ball support'

您也可以使用 lambda 函數:

data  = {"number": [1, 2, 3, 4, 5], "function": ['IT', 'IT application', 
'IT digital', 'other', 'Digital'] }
df = pd.DataFrame(data)  
df.function = df.function.apply(lambda x: 'IT' if 'IT' in x else x)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM