Reputation: 19
I have a DataFrame, for which I want to store values from the keyvalue
column into a variable, based on the value of keyname
.
Example DataFrame:
keyname keyvalue
A 100,200
B 300
C 400
Expected output:
v_A = [100, 200]
v_B = 300
v_C = 400
Upvotes: 2
Views: 3328
Reputation: 271
I can suggest two options..
Convert to a dictionary.. that will give you them as key value pairs, if that is what you want.
df.set_index('keyname').to_dict()
output:
{'keyvalue': {'A': '100,200', 'B': '300', 'C': '400'}}
Take a transpose and you will get them in columns of dataframe and then you can convert as list
dft=df.set_index('keyname').T
v_A=list(map(int, dft['A'][0].split(",")))
v_B=list(map(int, dft['B'][0].split(",")))
v_C=list(map(int, dft['C'][0].split(",")))
print(v_A)
print(v_B)
print(v_C)
output :
[100, 200]
[300]
[400]
Upvotes: 1
Reputation: 9701
While this is a more verbose approach, it's posted to demonstrate the basic concept for assigning keyvalue
values to a list
variable, based on the value of keyname
.
v_A = df.loc[df['keyname'] == 'A', 'keyvalue'].to_list()
v_B = df.loc[df['keyname'] == 'B', 'keyvalue'].to_list()
v_C = df.loc[df['keyname'] == 'C', 'keyvalue'].to_list()
Output:
['100,200']
['300']
['400']
Upvotes: 3
Reputation: 862701
Close, what you need is dictionary with keys and values, because concept of strings variables in python is not recommended:
d = df.set_index('keyname')['keyvalue'].to_dict()
Upvotes: 1