简体   繁体   English

我想将单个值添加到 Pandas 数据框中的多行

[英]I want to add a single value to multiple rows in a pandas data frame

Okay suppose I have a data frame A好的假设我有一个数据框 A

A: A:

col1 col2
 1    2
 3    4

I am not going to add two more columns to it col3 and col4 and want to populate it like so我不会再向它添加两列 col3 和 col4 并且想要像这样填充它

col1 col2 col3 col4
 1    2    5    6
 3    4    5    6

All the values of col3 need to be 5 and all the values of col4 need to be 6 no matter the number of rows无论行数如何,col3 的所有值都需要为 5,col4 的所有值都需要为 6

is there a way to do this without a loop?有没有办法在没有循环的情况下做到这一点?

You can add multiple columns with constant values for all rows like below:您可以为所有行添加具有常量值的多列,如下所示:

In [268]: df
Out[268]: 
   col1  col2
0     1     2
1     3     4

In [269]: df[['col3', 'col4']] = [5,6]

In [270]: df
Out[270]: 
   col1  col2  col3  col4
0     1     2     5     6
1     3     4     5     6

You can simply use assign function:您可以简单地使用分配功能:

df = df.assign(
    col3 = 5,
    col4 = 6
)

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

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