[英]How to divide each column of pandas Dataframe by a Series?
I have a pandas dataframe in which I want to divide each column by the same data series values for each row.我有一个 Pandas 数据框,我想在其中将每一列除以每一行的相同数据系列值。 Each column and the data series have the same length.
每列和数据系列的长度相同。 The data series has only float numbers but some cells in the dataframe have NaNs.
数据系列只有浮点数,但数据框中的某些单元格具有 NaN。
I tried various things but somehow I cannot get it solved.我尝试了各种方法,但不知何故我无法解决。
df = df.divide(data_series, axis=1)
Any suggestions?有什么建议?
many thanks!非常感谢!
I found the solution我找到了解决方案
Setting axis = 0 solves the issue.设置axis = 0 解决了这个问题。
df = df.divide(data_series, axis=0 )
many thanks非常感谢
Format your Series
index with df columns使用 df 列格式化您的
Series
索引
df.div(pd.Series([100,100,100],index=df.columns))
Out[132]:
A B id
0 0.01 0.02 0.01
1 0.02 0.03 0.01
2 0.04 0.00 0.03
3 0.05 0.06 0.01
4 0.08 0.09 0.03
5 0.09 0.07 0.03
Given dataframe df
and series s
, you can also use numpy
:给定数据帧
df
和 series s
,您还可以使用numpy
:
res = pd.DataFrame(df.values / s.values[:, None],
index=df.index, columns=df.columns)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.