2

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
2
  • Please add more details, so we can help you. With the current description your question is not clear. Commented Nov 27, 2020 at 8:33
  • use keyname as variable and keyvalue as value and store value in a variable Commented Nov 27, 2020 at 8:36

3 Answers 3

3

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']
Sign up to request clarification or add additional context in comments.

2 Comments

SyntaxError: can't assign to literal
(SyntaxError in comment above does not apply to the current (edited) answer.)
1

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()

2 Comments

TypeError: argument of type 'int' is not iterable
@ShivamPatel - so you need d = df.set_index('keyname')['keyvalue'].to_dict() only?
1

I can suggest two options..

  1. 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'}}
  1. 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]

1 Comment

I dont see why is better as culomns.. nd what that dictionary is better then jezreal answer?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.