简体   繁体   English

pandas 在多个数据框列上执行算术运算的最有效方法

[英]pandas most efficient way to execute arithmetic operations on multiple dataframe columns

my first post!我的第一篇文章! I'm running python 3.8.5 & pandas 1.1.0 on jupyter notebooks.我在 jupyter 笔记本上运行 python 3.8.5 & pandas 1.1.0。

I want to divide several columns by the corresponding elements in another column of the same dataframe.我想用同一数据帧的另一列中的相应元素划分几列。 For example:例如:

import pandas as pd
df = pd.DataFrame({'a': [2, 3, 4], 'b': [4, 6, 8], 'c':[6, 9, 12]})
df
    a   b   c
0   2   4   6
1   3   6   9
2   4   8   12

I'd like to divide columns 'b' & 'c' by the corresponding values in 'a' and substitute the values in 'b' and 'c' with the result of this division.我想将 'b' 和 'c' 列除以 'a' 中的相应值,并用该除法的结果替换 'b' 和 'c' 中的值。 So the above dataframe becomes:所以上面的数据框变成:

    a   b   c
0   2   2   3
1   3   2   3
2   4   2   3

I tried我试过

df.iloc[: , 1:] = df.iloc[: , 1:] / df['a']

but this gives:但这给出了:

    a   b   c
0   2   NaN NaN
1   3   NaN NaN
2   4   NaN NaN

I got it working by doing:我通过以下方式让它工作:

for colname in df.columns[1:]:
    df[colname] = (df[colname] / df['a'])

Is there a faster way of doing the above by avoiding the for loop?是否有通过避免 for 循环来执行上述操作的更快方法?

thanks, mk谢谢,马克

差不多了,使用divaxis=0

df.iloc[:,1:] = df.iloc[:,1:].div(df.a, axis=0)
df.b= df.b/df.a
df.c=df.c/df.a

or或者

df[['b','c']]=df.apply(lambda x: x[['b','c']]/x.a ,axis=1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Pandas:从 dataframe 中的多个其他列中减去某些列的最有效方法 - Pandas: The most efficient way to subtract some columns from multiple other columns in a dataframe Pandas:从DataFrame列创建词典字典的最有效方法 - Pandas: Most efficient way to make dictionary of dictionaries from DataFrame columns 将pandas dataframe列拆分为多个列的最有效方法 - Most efficient way to split a pandas dataframe column into several columns 检查 Pandas 数据框中列中的多个条件的最有效方法是什么? - What is the most efficient way to check several conditions in columns in a pandas dataframe? 计算 Pandas DataFrame 中一组列的平均值的最有效方法 - Most efficient way to calculate the mean of a group of columns in a pandas DataFrame 根据初始行中的值将熊猫数据帧的多行合并为一行,向该行添加新列的最有效方法? - Most efficient way to merge multiple rows of a pandas dataframe in to one row, adding new columns to the row, based on values in the initial rows? Memory 使用多列对 pandas dataframe 进行列表理解的有效方法 - Memory efficient way for list comprehension of pandas dataframe using multiple columns 在 pandas DataFrame 中取消嵌套(分解)多个列表列的有效方法 - Efficient way to unnest (explode) multiple list columns in a pandas DataFrame 在 pandas 中计算平方 dataframe 的最有效方法 - Most efficient way to compute a square dataframe in pandas pandas DataFrame 中映射列的最有效方法 - Most efficient way of mapping column in pandas DataFrame
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM