Skip to main content
 首页 » 编程设计

python之在 Pandas DataFrame 中添加新列时结果不一致。它是系列还是值

2024年11月24日9飞鱼

所以我知道我可以像这样在 Pandas 中简单地添加一个新列:

df 
===== 
  A 
1 5 
2 6 
3 7 
 
df['new_col'] = "text" 
 
df 
==== 
  A    new_col 
1 5    text 
2 6    text 
3 7    text 

我还可以根据对现有列的操作设置新列。

def times_two(x): 
    return x * 2 
 
df['newer_col'] = time_two(df.a) 
df 
==== 
  A    new_col   newer_col 
1 5    text      10 
2 6    text      12 
3 7    text      14 

但是,当我尝试对文本列进行操作时,出现了意外的 AttributeError。

df['new_text'] = df['new_col'].upper() 
AttributeError: 'Series' object has no attribute 'upper' 

它现在将值视为一个系列,而不是该“单元格”中的值。

为什么文本会发生这种情况而不是数字?如何使用基于现有文本列的新列更新我的 DF?

请您参考如下方法:

这是因为 * 运算符被实现为 mul运算符,而 upper 没有为 Series 定义。您必须使用为 Series 实现的 str.upper,其中 dtype 为 str:

In[53]: 
df['new_text'] = df['new_col'].str.upper() 
df 
 
Out[53]:  
   A new_col new_text 
1  5    text     TEXT 
2  6    text     TEXT 
3  7    text     TEXT 

这里没有魔法。

对于 df['new_col'] 这只是分配一个标量值并符合 广播 规则,其中标量沿着 df 的长度广播短轴,请参阅此解释:What does the term "broadcasting" mean in Pandas documentation?