简体   繁体   中英

Apply function to Pandas Data Frame Column

I am trying to apply the below function to a column in my pandas data frame. The column has entries like such --- > EMS: Diabetic Emergency

I am trying to split the entry and return the reason - ie Diabetic Emergency but free of the space after the ':'

I have tried the following:

def splitandstrip(column):
    for i in column:
        new = i.split(':')[1]
        new.strip()
    return new
df['response_reason'] = df.title.apply(splitandstrip)

Your function does not work as expected because str.strip returns a new string. The original string is unchanged. You could use

def splitandstrip(element):
   return element.split(':')[1].strip()

I would suggest using the Series.str accessor for vectorized string operations:

>>> df = pd.DataFrame(['EMS: Diabetic Emergency', 'ABC: DEF'], columns=['A'])
>>> df
                         A
0  EMS: Diabetic Emergency
1                 ABC: DEF
>>> df['A'].str.split(':').str.get(1).str.strip()
0    Diabetic Emergency
1                   DEF
Name: A, dtype: object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM