Skip to main content
 首页 » 编程设计

python之如何将系列或序列分配给 dask 数据框列

2025年04月02日13kenshinobiy

我的 dask dataframe 如下:

In [65]: df.head() 
Out[65]: 
   id_orig  id_cliente  id_cartao  inicio_processo  fim_processo  score  \ 
0      1.0         1.0        1.0              1.0           1.0    1.0 
1      1.0         1.0        1.0              1.0           1.0    1.0 
2      1.0         1.0        1.0              1.0           1.0    1.0 
3      1.0         1.0        1.0              1.0           1.0    1.0 
4      1.0         1.0        1.0              1.0           1.0    1.0 
 
   automatico  canal  aceito  motivo_recusa  variante 
0         1.0    1.0     1.0            1.0       1.0 
1         1.0    1.0     1.0            1.0       1.0 
2         1.0    1.0     1.0            1.0       1.0 
3         1.0    1.0     1.0            1.0       1.0 
4         1.0    1.0     1.0            1.0       1.0 

分配一个整数有效:

In [92]: df = df.assign(id_cliente=999) 
 
In [93]: df.head() 
Out[93]: 
   id_orig  id_cliente  id_cartao  inicio_processo  fim_processo  score  \ 
0      1.0         999        1.0              1.0           1.0    1.0 
1      1.0         999        1.0              1.0           1.0    1.0 
2      1.0         999        1.0              1.0           1.0    1.0 
3      1.0         999        1.0              1.0           1.0    1.0 
4      1.0         999        1.0              1.0           1.0    1.0 
 
   automatico  canal  aceito  motivo_recusa  variante 
0         1.0    1.0     1.0            1.0       1.0 
1         1.0    1.0     1.0            1.0       1.0 
2         1.0    1.0     1.0            1.0       1.0 
3         1.0    1.0     1.0            1.0       1.0 
4         1.0    1.0     1.0            1.0       1.0 

但是,在现有列中分配 Series 或任何其他可迭代对象的其他方法均无效。

我怎样才能做到这一点?

请您参考如下方法:

DataFrame.assign 接受任何标量或任何 dd.Series

df = df.assign(a=1)  # accepts scalars 
df = df.assign(z=df.x + df.y)  # accepts dd.Series objects 

如果您尝试分配一个 NumPy 数组或 Python 列表,那么您的数据可能足够小以适合 RAM,因此 Pandas 可能比 Dask.dataframe 更适合。

您也可以使用简单的 setitem 语法

df['a'] = 1 
df['z'] = df.x + df.y