简体   繁体   English

Dataframe在熊猫上划分系列

[英]Dataframe divide series on pandas

I need to divide each column of the matrix df1 into a single column of the matrix df2 . 我需要将矩阵df1每列分成矩阵df2的单个列。 To get a matrix with dimension df1 (3*2). 获得尺寸为df1 (3 * 2)的矩阵。

I need a result: dataframe[[1/6, 2/7, 3/8], [3/6, 4/7, 5,8]] 我需要一个结果:dataframe [[1 / 6,2 / 7,3 / 8],[3 / 6,4 / 7,5,8]]

df1 = pd.DataFrame(data = [[1,2,3],[3,4,5]], index = ['a','b'], columns = ['i','ii','iii'])
df2 = pd.DataFrame(data = [[6],[7],[8]], index = ['a','b','c'], columns = ['i'])

df1.div(df2, axis = 'columns')
=> does not work

for i in range(0,2)
    a = df1[df1.columns[i]] / df2
=> summarizes the result in one column

Thanks for your help 谢谢你的帮助

You can divide by Series converted to array by Series.values or Series.to_numpy for pandas 0.24+: 对于pandas 0.24+,您可以通过Series.valuesSeries.to_numpySeries转换为数组除以:

df = df1.div(df2['i'].values)
#pandas 0.24+
#df = df1.div(df2['i'].to_numpy())
print (df)
          i        ii    iii
a  0.166667  0.285714  0.375
b  0.500000  0.571429  0.625

Here's one way: 这是一种方式:

pd.DataFrame(df1.values/ df2.values.T, columns=df1.columns)

       i        ii      iii
0  0.166667  0.285714  0.375
1  0.500000  0.571429  0.625

with Series : 系列:

s = pd.Series(df2.values.flatten().tolist(), index=df1.columns)
print(df1.div(s))

output : 输出:

          i        ii    iii
a  0.166667  0.285714  0.375
b  0.500000  0.571429  0.625

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM