简体   繁体   English

Python:可从每一行提取数据的字典

[英]Python: Dictionary that will pull data from every row

I'm trying to create a dictionary that will give me the values for each state that I plug into the key value. 我正在尝试创建一个字典,该字典将为我提供插入键值的每个状态的值。 Here's my code: 这是我的代码:

sat_partic = {'State': 'Participation'}

but this just gives me the variables i inputted in the curly brackets. 但这只是给了我在大括号中输入的变量。

I appreciate your help and suggestions. 感谢您的帮助和建议。

        State   Participation   
0       Alabama     5%  
1       Alaska     38%  
2       Arizona    30%  
3       Arkansas   20%  
4       California 14%  

The complete answer: 完整答案:

d = df.set_index('State')['Participation'].to_dict()

However, in many situations this is not necessary, since you can use pd.Series.get with similar functionality. 但是,在很多情况下这不是必需的,因为可以将pd.Series.get与类似的功能一起使用。

For example, you can use: 例如,您可以使用:

d = df.set_index('State')['Participation']

Then use d.get('Alabama') , etc, to retrieve Participation. 然后使用d.get('Alabama')等检索参与。

Dictionaries use key-value pairs. 字典使用键值对。 So you could use the states as keys (each state occurs only once, right?) and the percentages as values: 因此,您可以将状态用作键(每个状态仅发生一次,对吧?),并将百分比用作值:

sat_partic = {"Alabama": 5, "Alaska": 38, "Arizona": 30, ...}

I'm not entirely sure if below code solves your purpose. 我不确定下面的代码是否可以解决您的目的。 But, here I go. 但是,我走了。 You can use namedtuple 您可以使用namedtuple

from collections import namedtuple

columns = 'State Participation'

STAT_PARTIC = namedtuple('stat_partic', columns)

print (STAT_PARTIC._fields)
input_data = ['Alabama 5%', 'Alaska 38%', 'Arizona 30%', 'Arkansas 20%',
              'California 14%']

list_all_data = []

for line in input_data:
    data = line.split()
    stat_part = STAT_PARTIC(*data)
    list_all_data.append(stat_part)

print (list_all_data[0].State)
print (list_all_data[0].Participation)

Could you show the desirable output? 您能显示理想的输出吗? I am not sure if I understood well. 我不确定我是否理解得很好。 But... 但...

Why not using pandas library and changing State names into index? 为什么不使用熊猫库并将州名称更改为索引?

import pandas as pd

ser1 = pd.Series(['5%','38%','30%','20%','14%'],['Alabama','Alaska','Arizona','Arkansas','California'])

ser1[:]

Out: 出:

Alabama        5%
Alaska        38%
Arizona       30%
Arkansas      20%
California    14%
dtype: object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM