简体   繁体   English

从数据框中分配变量

[英]Assigning variables from dataframe

I have the below dataframe:我有以下数据框:

df: df:

Name    Value
A       30
B       40
C       50

How can i read this dataframe so that i can use these values as variables for my code?我如何读取这个数据帧,以便我可以将这些值用作我的代码的变量?

Like:喜欢:

A=30
B=40
C=50

I was trying something on these lines:我在这些方面尝试了一些东西:

for n in range(len(df)):
    A = df.at[n, "A"]
    B = df.at[n, "B"]
    C = df.at[n, "C"]

I think simliest is create Series by index from Name column by DataFrame.set_index and then select by labels by Series.at or Series.loc :我认为最简单的方法是通过DataFrame.set_indexName列的索引创建Series ,然后通过Series.atSeries.loc标签选择:

s = df.set_index('Name')['Value']
print (s)
Name
A    30
B    40
C    50
Name: Value, dtype: int64

A = s.at["A"]
B = s.at["B"]
C = s.at["C"]

print (A,B,C)
30 40 50

Or if want filter by columns names it is possible by boolean indexing , but output is Series, so for first value use Series.iat or Series.iloc :或者,如果Series.iat列名称过滤,可以通过boolean indexing ,但输出是系列,因此对于第一个值,请使用Series.iatSeries.iloc

A = df.at[df['Name'].eq("A"), 'Value'].iat[0]
B = df.at[df['Name'].eq("B"), 'Value'].iat[0]
C = df.at[df['Name'].eq("C"), 'Value'].iat[0]

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

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