Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic column name in panda dataframe evaluation

Tags:

python

pandas

I'm referencing a dataframe as follows (Sales is the column name):

total = pd.to_numeric(sales_df.Sales.str.replace("$", "")).sum()

But I don't want Sales to be hard coded, I want a variable to make it dynamic. How is this done?

TIA

like image 712
mr-sk Avatar asked Sep 15 '26 21:09

mr-sk


1 Answers

You can should index your columns by using square brackets:

df['col_name']

So when you accept the input as a str you can just do:

total = pd.to_numeric(sales_df[user_input_name].str.replace("$", "")).sum() 

Additionally accessing columns as an attribute can lead to ambiguous behaviour. Such as having a column named index and you try to do df.index which may have different values to the column df['index'] or if you had a column named the same as any valid df method like sum or var then this will lead to syntax errors.

So I strongly advise you use square brackets to select columns.

like image 114
EdChum Avatar answered Sep 18 '26 11:09

EdChum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!