[英]Elegant way to add an array on each column dataframe pandas
I would like to add a 1D array on each column of a pandas dataframe. 我想在熊猫数据框的每一列上添加一维数组。
Exemple : 范例:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(0,100,size=(4, 4)), columns=list('ABCD'))
s = np.random.randint(0,100,size=(4, 1))
Is there a way more elegant way than : 有没有比以下更优雅的方法:
for col in df.columns:
df[col] = df[col] + s
Obviously, summ = df + s doesn't work 显然,summ = df + s不起作用
您可以使用numpy level来做到这一点:
df.iloc[:] = df.values+ s
np.random.seed(0)
df = pd.DataFrame(np.random.randint(0,100,size=(4, 4)), columns=list('ABCD'))
s = np.random.randint(0,100,size=(4, 1))
df
A B C D
0 44 47 64 67
1 67 9 83 21
2 36 87 70 88
3 88 12 58 65
s
array([[39],
[87],
[46],
[88]])
Use df.add
. 使用df.add
。 You'll need to unravel s
, because of its dimension. 由于其尺寸,您需要解开s
。
df.add(s.ravel(), axis=0)
A B C D
0 83 86 103 106
1 154 96 170 108
2 82 133 116 134
3 176 100 146 153
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.