fred.schwartz
fred.schwartz

Reputation: 2155

Reference Pandas dataframe column headers from dictionary

I have a dataframe, df with columns headers xx, yy, zz, aaa

I then have lists

A=['xx']
B=['yy']
C=['zz']

can I reference these headers from this dictionary?

dic={'key1':['A','B'],
key2: ['C','D']}

df[dic[key1[0]]]

giving the output of just column xx?

   xx
0  44
1  44
2  44
3  33

Upvotes: 1

Views: 1235

Answers (1)

WurzelseppQX
WurzelseppQX

Reputation: 540

Yes you can. Just pass the lists itself into the dictionary instead of a string with the name of the list. Also you need to modify the call of your dictionary (see Explanation below). Try this:

dic={'key1':[A,B], 'key2': [C,D]}
col = df[dic['key1'][0][0]]
print(col)

Explanation:

Your goal is to get the dataframe column df['xx']. To get the 'xx' from the dictionary you need to get the value of the desired key in the dictionary. There was a typo in your call, as your key is a string, so you you need to write dic['key1']. This will return you the list [['xx'],['yy']] which returns 2 sublists. From this list you need to get the first sublist, which has index [0]. So, dic['key1'][0] will give you the sublist ['xx']. But as this is also a list and you actually want the first element of it, you again have to use the index [0]. Hence, the call dic['key1'][0][0] will give you the desired string 'xx'.

Remark: If A really only contains a list with one single element, I recommend not to use a list and just write A = 'xx'. You can then save the second [0] in call of the dictionary and the call of the dataframe column will be like: df[dic['key1'][0]]

Upvotes: 1

Related Questions