简体   繁体   中英

Python Pandas replace substring if string starts with

I am trying to write the following function:

def d (row):
    if df['name'].str.startswith('"'):
        return df['name'].str.replace("'","''")
    else:
        return df['name']
df['name2'] = df.apply(lambda row: d(row), axis=1)

I am trying to add a second apostrophe whenever a string has a single apostrophe within a contraction. this only appears when i have double quoted strings.

I continue to get a ' KeyError: ('name', occurred at index 0')

this only happens a few times in my dataset, but i need to replace "jack's place" with "jack''s place" so that i can inject this into a sql query.

Why can't you do a full replace:

df['name2'] = df['name'].str.replace('\'', '"')
print(df)

           name         name2
0           ABC           ABC
1           SDF           SDF
2  jack's place  jack"s place
3  jack's place  jack"s place
4  jack's place  jack"s place

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