简体   繁体   English

Python Pandas 如果字符串以

[英]Python Pandas replace substring if string starts with

I am trying to write the following function:我正在尝试编写以下 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')我继续得到一个' KeyError:('name',发生在索引 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.这在我的数据集中只发生了几次,但我需要将“jack's place”替换为“jack's place”,以便我可以将其注入 sql 查询中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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