Python 将多列除以熊猫中的另一列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34540567/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:08:18  来源:igfitidea点击:

Divide multiple columns by another column in pandas

pythonpandas

提问by itzy

I need to divide all but the first columns in a DataFrame by the first column.

我需要将 DataFrame 中除第一列以外的所有列除以第一列。

Here's what I'm doing, but I wonder if this isn't the "right" pandas way:

这是我正在做的事情,但我想知道这是否不是“正确”的熊猫方式:

df = pd.DataFrame(np.random.rand(10,3), columns=list('ABC'))

df[['B', 'C']] = (df.T.iloc[1:] / df.T.iloc[0]).T

Is there a way to do something like df[['B','C']] / df['A']? (That just gives a 10x12 dataframe of nan.)

有没有办法做类似的事情df[['B','C']] / df['A']?(这只是给出了一个 10x12 的数据帧nan。)

Also, after reading some similar questions on SO, I tried df['A'].div(df[['B', 'C']])but that gives a broadcast error.

另外,在阅读了一些关于 SO 的类似问题后,我尝试过,df['A'].div(df[['B', 'C']])但这给出了广播错误。

采纳答案by Dthal

I believe df[['B','C']].div(df.A, axis=0)and df.iloc[:,1:].div(df.A, axis=0)work.

我相信df[['B','C']].div(df.A, axis=0)df.iloc[:,1:].div(df.A, axis=0)工作。