Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

python - Dynamic column name in panda dataframe evaluation

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...