亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 Python 中訪問字符串中的某些值

如何在 Python 中訪問字符串中的某些值

慕妹3146593 2022-06-14 15:06:02
我只需要提取字符串中的特定元素值。下面是我使用 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
查看完整描述

1 回答

?
慕蓋茨4494581

TA貢獻1850條經驗 獲得超11個贊

希望這會起作用,讓您的數據是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)


查看完整回答
反對 回復 2022-06-14
  • 1 回答
  • 0 關注
  • 115 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號