1

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
5
  • what’s in the lists? column names as strings? Commented Feb 24, 2019 at 20:22
  • sorry yes, strings Commented Feb 24, 2019 at 20:23
  • this is a very simplified version of what I'm trying to do Commented Feb 24, 2019 at 20:24
  • I'm getting an error saying ''A" is not a column in df, when really I'm trying to pull 'xx' from the list A Commented Feb 24, 2019 at 20:25
  • This error is because you are passing the name of the list as a string and not as the name A itself. Commented Feb 24, 2019 at 21:02

1 Answer 1

1

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]]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.