从字符串中剥离第一个和最后一个引号时,“tuple”对象没有属性“startswith”

2024-09-27 04:19:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在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”


Tags: 数据对象text元素dfstring字典prod
1条回答
网友
1楼 · 发布于 2024-09-27 04:19:10

您使用的是pandas.Series.iteritems,它实际上迭代(索引、值)元组。因此,要使代码正常工作,您应该尝试如下更改循环:

for label, text in df.iteritems():
    # process text

但我建议您查看关于working with text的熊猫文档。例如,您可以直接为序列via ^{} accessor编制索引

相关问题 更多 >

    热门问题