如何替换 json 中的单引号 like pandas 中的列

How to replace single quotes in a json like column in pandas

我在数据框中有一列,其值如下所示:

{'id': 22188, 'value': 'trunk'}
{'id': 22170, 'value': 'motor'}

我想将单引号替换为双引号以用作 json 字段。我正在尝试:

df['column'] = df['column'].replace({'\'': '"'}, regex=True)

但没有任何变化。

我该怎么做?

预期结果:

{"id": 22188, "value": "trunk"}
{"id": 22170, "value": "motor"}

不用特别转义字符,用反义字就可以了。 也不需要使用正则表达式 而且你必须使用 str 访问器来进行字符串替换

df['column'] = df['column'].str.replace("'",'"', regex=False)

适用于字符串字段

>>> pd.Series(["{'id': 22188, 'value': 'trunk'}","{'id': 22170, 'value': 'motor'}"])
0    {'id': 22188, 'value': 'trunk'}
1    {'id': 22170, 'value': 'motor'}
dtype: object
>>> pd.Series(["{'id': 22188, 'value': 'trunk'}","{'id': 22170, 'value': 'motor'}"]).str.replace("'",'"')
0    {"id": 22188, "value": "trunk"}
1    {"id": 22170, "value": "motor"}
dtype: object
>>>

字典失败 => 先用astype(str)

转换
>>> pd.Series([{'id': 22188, 'value': 'trunk'},{'id': 22170, 'value': 'motor'}])
0    {'id': 22188, 'value': 'trunk'}
1    {'id': 22170, 'value': 'motor'}
dtype: object
>>> pd.Series([{'id': 22188, 'value': 'trunk'},{'id': 22170, 'value': 'motor'}]).str.replace("'",'"')
0   NaN
1   NaN
dtype: float64
>>> pd.Series([{'id': 22188, 'value': 'trunk'},{'id': 22170, 'value': 'motor'}]).astype(str).str.replace("'",'"')
0    {"id": 22188, "value": "trunk"}
1    {"id": 22170, "value": "motor"}
dtype: object