我试图在pandas数据框(对象的第一个元素和最后一个元素)中去掉嵌套字典周围的单引号。我正在遍历列元数据中的每一行
隐藏在引号内的嵌套字典示例如下:
'{"dek": "<p>Don\'t forget to buy a card</p>", "links": {"edit": {"dev": "//patty-menshealth.feature.hearstapps.net/en/content/edit/76517422-96ad-4b5c-a24a-c080c58bce0c", "prod": "//patty-menshealth.prod.com/en/content/edit/76517422-96ad-4b5c-a24a-c080c58bce0c"}}}'
我尝试了以下方法:
def string_format(df):
for text in df.iteritems():
if text.startswith("'") and text.endswith("'"):
text = text[1:-1]
return text
string_format(df["metadata"])
返回AttributeError:“tuple”对象没有属性“startswith”
您使用的是pandas.Series.iteritems,它实际上迭代(索引、值)元组。因此,要使代码正常工作,您应该尝试如下更改循环:
但我建议您查看关于working with text的熊猫文档。例如,您可以直接为序列via ^{} accessor 编制索引
相关问题 更多 >
编程相关推荐