[英]Map values from a dataframe
I have a dataframe with the correspondence between two values: 我有一个数据框,其中包含两个值之间的对应关系:
A another list with only one of the variables: 另一个只包含其中一个变量的列表:
l = ['a','b','c']
I want to make the mapping like: 我想使映射像:
df[l[0]]
and get 1 得到1
df[l[1]]
and get 2 得到2
As if it was a dictionary, how can I do that? 好像它是一本字典,我怎么能这样做?
Are you looking for something like this? 你在找这样的东西吗?
df.loc[df['key']==l[0], 'value']
returns 回报
0 1
1 1
Another way would be to set_index of the df to key. 另一种方法是将df的set_index设为key。
df.set_index('key', inplace = True)
df.loc[l[0]].values[0]
Another way is map by Series
or by dict
but is necessary unique value of key
s, drop_duplicates
helps: 另一种方式是按Series
或按dict
映射,但是key
s的必要唯一值, drop_duplicates
有助于:
df = pd.DataFrame({'key':list('aabcc'),
'value':[1,1,2,3,3]})
s = df.drop_duplicates('key').set_index('key')['value']
print (s)
key
a 1
b 2
c 3
Name: value, dtype: int64
d = df.drop_duplicates('key').set_index('key')['value'].to_dict()
print (d)
{'c': 3, 'b': 2, 'a': 1}
l = ['a','b','c']
print (s[l[0]])
1
print (d[l[1]])
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.