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
S3DEV
  • 8,768
  • 3
  • 31
  • 42
Shivam Patel
  • 19
  • 1
  • 8

3 Answers3

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']
S3DEV
  • 8,768
  • 3
  • 31
  • 42
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()
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
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]
Johnson Francis
  • 249
  • 3
  • 17