Shivam Patel
Shivam Patel

Reputation: 19

Pandas: How to assign one column value to a variable, based on another column?

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

Answers (3)

Johnson Francis
Johnson Francis

Reputation: 271

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]

Upvotes: 1

s3dev
s3dev

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

jezrael
jezrael

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

Related Questions