如何从Ordereddicts数组中提取值?

2024-04-26 06:24:11 发布

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

如果我有一个csv文件行,其中一列中有ordereddicts,那么如何创建一个新列,使用python(3.+)/pandas(.18)提取每个ordereddict的单个元素?在

这里有一个例子。我的专栏attributes在ordereddicts中隐藏了billingPostalCodes。我只关心用billingPostalCodes创建一个列。在

以下是我现在的数据:

 import pandas as pd
 from datetime import datetime
 import csv
 from collections import OrderedDict

 df = pd.read_csv('sf_account_sites.csv')
 print(df)

产量:

^{pr2}$

我个人知道如果我这样做:

dict = OrderedDict([(u'attributes', OrderedDict([(u'type', u'Account'), (u'url', u'/services/data/v29.0/sobjects/Account/001d000001tKZmWAAW')])), (u'BillingPostalCode', u'85020')])

print(dict['BillingPostalCode'])

结果我会拿回85020。在

我要怎样才能让它看起来像这样?在

 id    zip_codes  
  1    85020
  2    55555
  ...

我必须使用应用功能吗?一个for循环?我尝试了很多不同的方法,但是我在数据帧上什么都做不到。在

提前谢谢,如果需要更具体的话,请告诉我。在


Tags: csv数据fromimportpandasdfdatetimeaccount
1条回答
网友
1楼 · 发布于 2024-04-26 06:24:11

我花了一段时间来解决这个问题,但问题是通过执行以下操作来解决的:

df.apply(lambda row: row["attributes"]["BillingPostalCode"], axis = 1)

这里的诀窍是要注意axis = 1强制pandas遍历每一行,而不是每一列(这是默认设置,如docs所示)。在

DataFrame.apply(func, axis=0, broadcast=False, raw=False, reduce=None, args=(), **kwds)

Applies function along input axis of DataFrame.

Objects passed to functions are Series objects having index either the DataFrame’s index (axis=0) or the columns (axis=1). Return type depends on whether passed function aggregates, or the reduce argument if the DataFrame is empty.

Parameters:

  • func : function Function to apply to each column/row
  • axis : {0 or ‘index’, 1 or ‘columns’}, default 0
    • 0 or ‘index’: apply function to each column
    • 1 or ‘columns’: apply function to each row

从那里,一个简单的问题是首先提取相关列(在本例中是attributes),然后从那里只提取BillingPostalCode。在

您需要格式化生成的DataFrame,以获得正确的列名。在

相关问题 更多 >