简体   繁体   English

在每列数据框熊猫上添加数组的优雅方法

[英]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.

相关问题 是否有 pandas 方法通过特定列值为每一行添加 dataframe - Is there a pandas way to add a dataframe for each row by a specific column value 有没有一种优雅的方法来迭代索引和熊猫数据框的一列? - Is there an elegant way to iterate over index and one column of a pandas dataframe? 基于每个组填充pandas列中的值的高效且优雅的方法 - Efficient and elegant way to fill values in pandas column based on each groups 有没有办法向pandas数据框添加新列,将新列的每个唯一值附加到数据帧的每个现有行? - Is there a way to add a new column to a pandas dataframe, appending each unique value of the new column to every existing row of the dataframe? 是否有任何优雅的方法来定义具有dtype数组列的数据框? - Is there any elegant way to define a dataframe with column of dtype array? Python-在Pandas面板的每个数据框中添加一列 - Python - Add a column to each dataframe of a Pandas Panel 将新列添加到pandas数据帧的有效方法 - Efficient way to add new column to pandas dataframe 创建Pandas DataFrame的更优雅的方法 - More elegant way of creating Pandas DataFrame 迭代到多级熊猫DataFrame的优雅方法 - Elegant way to iterate into a multilevel pandas DataFrame 在 Pandas Dataframe 中用字符串交换双打的优雅方式? - Elegant Way to Swap Doubles With Strings In Pandas Dataframe?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM