我在ipython工作;我有一个Yaml文件和一个与我的Yaml文件对应的[thomas]id列表(thomas:-文件的第三行)。下面只是文件的一小部分。完整的文件可以在这里找到(https://github.com/108michael/congress-legislators/blob/master/legislators-historical.yaml)
- id:
bioguide: C000858
thomas: '00246'
lis: S215
govtrack: 300029
opensecrets: N00002091
votesmart: 53288
icpsr: 14809
fec:
- S0ID00057
wikipedia: Larry Craig
house_history: 11530
name:
first: Larry
middle: E.
last: Craig
bio:
birthday: '1945-07-20'
gender: M
religion: Methodist
terms:
- type: rep
start: '1981-01-05'
end: '1983-01-03'
state: ID
district: 1
party: Republican
- type: rep
start: '1983-01-03'
end: '1985-01-03'
state: ID
district: 1
party: Republican
我要解析文件,并且对于列表中与[thomas:]中的id对应的每个id,我要检索以下内容:[fec]:(可能有多个,我需要所有这些内容)[name:][first:][middle:][last:];[bio:][birthday:];[terms:](很可能有多个术语,我需要所有术语)[type:][start:][国家:][缔约方:]。最后,也可能存在fec数据不可用的情况。
1)我应该如何存储数据?我对Python(我的第一种编程语言)还比较陌生,不知道如何存储数据。直觉上,我会说是字典;然而最重要的是访问和数据检索的方便性。以前,我将类似的嵌套数据存储为csv。这种方法似乎有点笨重。如果我能列出字典(我正在检索的数据)的列表(来自我拥有的thomas id),这似乎是一个理想的选择。
2)我不知道如何设置for/while语句,以便只检索与thomas id列表对应的数据。
我开始写我所期望的将信息写入CSV的代码:
import pandas as pd
import yaml
import glob
import CSV
df = pd.concat((pd.read_csv(f, names=['date','bill_id','sponsor_id']) for f in glob.glob('/home/jayaramdas/anaconda3/df/s11?_s_b')))
outputfile = open('sponsor_details', 'W', newline='')
outputwriter = csv.writer(outputfile)
df = df.drop_duplicates('sponsor_id')
sponsor_list = df['sponsor_id'].tolist()
with open('legislators-historical.yaml', 'r') as f:
data = yaml.load(f)
for sponsor in sponsor_list:
where sponsor == data[0]['thomas']:
x = data[0]['thomas']
a = data[0]['name']['first']
b = data[0]['name']['middle']
c = data[0]['name']['last']
d = data[0]['bio']['gender']
e = data[0]['bio']['religion']
for fec in data[0]['id']:
c = fec.get('fec')
for terms in data[0]['id']:
t = terms.get('type')
s = terms.get('start')
state = terms.get('state')
p = terms.get('party')
outputwriter.writerow([x, a, b, c, d, e, c, t, s, state, p])
outputfile.flush()
我得到以下错误:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-48-057d25de7e11> in <module>()
15
16 for sponsor in sponsor_list:
---> 17 if sponsor == data[0]['thomas']:
18 x = data[0]['thomas']
19 a = data[0]['name']['first']
KeyError: 'thomas'
我认为您可以尝试解析YAML并将其加载到数据帧,normalizing它:
输出:
更新:
以下版本将筛选您的输入数据,以便只处理包含“thomas”和“fec”的记录:
输出:
PS如您所见,这将复制您的行(请参见:
id.thomas
和id.fec
),以便将其显示为数据帧更新2
您可能还希望将“id.fec”中的列表转换为列,但我将在其他数据帧中执行此操作:
输出:
相关问题 更多 >
编程相关推荐