簡體   English   中英

pandas中如何從深度字典中提取鍵值 || Python || dataframe

[英]How to extract key value from deep dictionary in pandas || Python || dataframe

我正在發出請求調用並將數據存儲到 JSON,然后從那里我將 JSON 加載到 pandas DataFrame,好消息是它像魔術一樣工作。 但是,不幸的是,我在數據框中的幾列中提供了深層詞典。 我無法從中提取關鍵值。 我附上了帶有幾列的 CSV 文件,其中重要的一列是“訪客”列。

我一直在查看 inte.net 並嘗試了很多東西,以至於現在我對什么是正確的什么是錯誤的感到很困惑。 下面是我的代碼和試驗的快照。

Adata = response.json()

## Loading the Json Data to DataFrame
df = pd.DataFrame(Adata)
df = df.astype(str)

## Exporting the Dataframe to csv file.
df.to_csv('Appointments.csv')

## Trying to create a new column with key values that I want out of guest column.
AB = df[['guest']]
print(AB)

BA = df['guest'].str.strip().to_frame()
print(BA)

BA.to_csv('BA_sheet.csv')

##Loaded single row and tried to check if I can do something about it.
test = {'id': '4b75bc9a-dc86-4fb5-a80a-46703e3d97b0', 'first_name': 'ASHISH ', 'last_name': 'PATEL', 'gender': 1, 'mobile': {'country_id': 0, 'number': None, 'display_number': None}, 'email': None, 'indicator': '0@0@0@0@0@0@0@x@0@0@0@0@2#0@0@0@0', 'lp_tier_info': '0@x', 'is_virtual_user': False, 'GuestIndicatorValue': {'HighSpender': None, 'Member': 0, 'LowFeedback': None, 'RegularGuest': None, 'FirstTimer': None, 'ReturningCustomer': None, 'NoShow': None, 'HasActivePackages': None, 'HasProfileAlerts': None, 'OtherCenterGuest': None, 'HasCTA': None, 'Dues': None, 'CardOnFile': None, 'AutoPayEnabled': None, 'RecurrenceAppointment': None, 'RebookedAppointment': None, 'hasAddOns': None, 'LpTier': None, 'IsSurpriseVisit': None, 'CustomDataIndicator': None, 'IsGuestBirthday': None}}
df3 = pd.DataFrame(test)
#print (df3)
df3.to_csv('df3_testsheet.csv')


## Trying to lambda function to extract the data that I want.
AB = AB.map(lambda x: (x.guest['id'], x.guest['first_name'], x.guest['last_name'])).toDF(['id', 'first_name', 'last_name'])
print(AB)

## Trying regex to get the desired data.
pp = re.findall(r"'first_name'.*?'(.*?)'", str(AB))
print(pp)

我只想從該來賓列的字典中提取idfirst_namelast_name 使用此鏈接訪問 csv 文件,該文件的結果為 DataFrame。

你這樣做的方式是,你試圖從 dict 的 str 表示中提取你的first_namelast_nameid鍵。 您可以使用內置的eval將其轉換回字典(如果您不確定數據的來源,則不推薦),或者使用ast模塊中的ast.literal_eval function。

import ast

df['guest'] = df['guest'].apply(ast.literal_eval)

將來賓詞典作為 dict 對象后,您可以簡單地應用pd.Series將其轉換為單獨的DataFrame

guest_df = df['guest'].apply(pd.Series)

guest_df['id'] # => gives you id
guest_df['first_name'] # => gives you first name
guest_df['last_name'] # => gives you last name

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM