![](/img/trans.png)
[英]Function to modify row values using df.apply or similar in Pandas
[英]Using pandas df.apply with a function that returns a dictionary
我有一個 JSON 文件,我最初從中讀取到 pandas DF。 它看起來像這樣:
{
...
...
"Info": [
{
"Type": "A",
"Desc": "4848",
...
},
{
"Type": "P",
"Desc": "3763",
...
},
{
"Type": "S",
"Desc": "AUBERT",
...
}
],
...
}
我有一個函數可以遍歷“信息”字段,並根據“類型”將信息存儲到字典中並返回該字典。 然后我想使用df.apply
根據存儲在字典中的值在我的 df 中創建新列。 請看下面:
def extract_info(self):
def extract_data(df):
dic = {'a': None, 'p': None, 's': None}
for info in df['Info']:
if info['Type'] == "A":
dic['a'] = info['Desc']
if info['Type'] == "P":
dic['p'] = info['Desc']
if info['Type'] == "S":
dic['s'] = info['Desc']
return dic
self.df['A'] = self.df.apply(extract_data, axis=1)['a']
self.df['P'] = self.df.apply(extract_data, axis=1)['p']
self.df['S'] = self.df.apply(extract_data, axis=1)['s']
return self
我也嘗試過這樣做:
self.df['A'] = self.df.apply(lambda x: extract_data(x['a']), axis=1)
但這些對我不起作用。 我查看了其他關於將df.apply
與返回字典的函數一起使用的 SO 帖子,但沒有找到我的案例所需的內容。 請幫忙。
我可以編寫 3 個單獨的函數,例如extract_A
、 extract_B
和extract_C
並分別返回單個值以使df.apply
工作,但這意味着運行 for 循環 3 次,每個函數一個。 也歡迎使用字典以外的任何其他建議。 謝謝。
我可以將它們存儲為變量並將它們返回到我的extract_data
函數中,而不是將其存儲在字典中。 然后我可以直接使用df.apply
中的result_type
參數將這些值分配給我的self.df
中的新列。
def extract_info(self):
def extract_data(df):
a = None
p = None
s = None
for info in df['Info']:
if info['Type'] == "A":
a = info['Desc']
if info['Type'] == "P":
p = info['Desc']
if info['Type'] == "S":
s = info['Desc']
return a, p, s
self.df[['A', 'P', 'S']] = self.df.apply(extract_data, axis=1, result_type="expand")
return self
輸出:
A P S
0 4848 3763 AUBERT
...
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.