0

I'm not quite sure how to phrase this question, so let me illustrate with an example.

Let's say you have a Pandas dataframe called store_df with a column called STORE_NUMBER. There are two ways to access a given column in a Pandas dataframe:

store_df['STORE_NUMBER']

and

store_df.STORE_NUMBER

Now let's say that you have a variable called column_name which contains the name of a column in store_df as a string. If you run

store_df[column_name]

All is well. But if you try to run

store_df.column_name

Python throws an AttributeError because it is looking for a literal column named "column_name" which doesn't exist in our hypothetical dataframe.

My question is: Is there a way to look up columns dynamically using second syntax (dot notation)? Not so much because there is anything wrong with the first syntax (list notation), but because I am curious if there is some advanced feature of Python that allows users to replace variable names with their value as another variable (in this case a state variable of the dataframe). I know there is the exec function but I was wondering if there was a more elegant solution. I tried

store_df.{column_name}

but received a SyntaxError.

  • Yes, you want `getattr`, But you really should just use the first syntax (which is pandas best-practice anyway) – juanpa.arrivillaga Jun 13 '22 at 18:55
  • @juanpa.arrivillaga Thanks! I will probably continue to use the first syntax, but I was just curious if it was possible using the second syntax. –  Jun 13 '22 at 19:07

1 Answers1

0

Would getattr(df, 'column_name_as_str') be the kind of thing you're looking for, perhaps?

Jinx
  • 511
  • 1
  • 3
  • 10
  • Yes, that is exactly what I am looking for! Thank you! I did not know about the `getattr` function. –  Jun 13 '22 at 19:07