如何在Python中访问字符串中的某些值

问题描述 投票:0回答:1

我只需要提取字符串中的特定元素值。以下是我使用Facebook AdsInsight API获取AdsInsight数据的代码。

class LibFacebook:
    def __init__(self, app_id, app_secret, access_token, ad_account_id):
        FacebookAdsApi.init(app_id, app_secret, access_token)
        self.account = AdAccount(ad_account_id)
      #get ads insight
        insights = self.account.get_insights(fields=[
        AdsInsights.Field.campaign_id,
        AdsInsights.Field.actions,
], params={
        'level': AdsInsights.Level.campaign,
        })
        print(insights)

输出

<AdsInsights> {
    "campaign_id": "23843294609751234",
    "actions": [
        {
            "action_type": "post_reaction",
            "value": "1"
        },
        {
            "action_type": "landing_page_view",
            "value": "78"
        },
        {
            "action_type": "link_click",
            "value": "163"
        }
       ]

问题:与campaign_id值(23843294609751234)一起,我只需要landing_page_view的值,即78(而不是其他操作项)并将其放在df中。如何访问它们?

其他信息:AdsInsights.Field.actions是字符串类型。

type(AdsInsights.Field.actions)

str
python dataframe facebook-graph-api facebook-python-business-sdk
1个回答
1
投票

希望这行得通,让我们以您的数据为AdsInsights对象的列表

obj = [{
    "campaign_id": "23843294609751234",
    "actions" : [

            {
                "action_type": "post_reaction",
                "value": "1"
            },
            {
                "action_type": "landing_page_view",
                "value": "78"
            },
            {
                "action_type": "link_click",
                "value": "163"
            }
           ]
},

 {
    "campaign_id": "112233",
    "actions" : [

            {
                "action_type": "post_reaction",
                "value": "1"
            },
            {
                "action_type": "landing_page_view",
                "value": "100"
            },
            {
                "action_type": "link_click",
                "value": "163"
            }
           ]
}]

您可以得到这样的结果

result_arr = []
for i in obj:
    datadict = {}  
    datadict["campaign_id"] = i.get("campaign_id")
    for action in i.get("actions"):
        if action.get("action_type") == "landing_page_view":
            datadict["value"]= action.get("value")
            result_arr.append(datadict)

result_arr将是

[{'campaign_id': '23843294609751234', 'value': '78'},
 {'campaign_id': '112233', 'value': '100'}]

下一步将字典列表转换为数据框

df=pd.DataFrame(result_arr)
© www.soinside.com 2019 - 2024. All rights reserved.