您的位置: 网站首页> 大家问> 当前文章

pandas空dataframe对象添加列cannot set a frame with no defined index and a scalar

老董2021-08-16160围观,142赞

  用了一段时间pandas,顺带写了个pandas教程栏目。今天突然发现空df对象进行增加1列不起效果,并且采用多种方式分别测试了下皆不能行通。

  1、直接赋值

import pandas as pd

df = pd.DataFrame()
print(df)
print('============')
df['A'] = 1
print(df)
Empty DataFrame
Columns: []
Index: []
============
Empty DataFrame
Columns: [A]
Index: []


  2、loc赋值

import pandas as pd

df = pd.DataFrame()
print(df)
print('============')
df.loc[:,'A'] = 2
ValueError: cannot set a frame with no defined index and a scalar


  3、assign函数

import pandas as pd

df = pd.DataFrame()
print(df)
print('============')
df2 = df.assign(A=lambda x: 2)
print(df2)
Empty DataFrame
Columns: []
Index: []
============
Empty DataFrame
Columns: [A]
Index: []


  那么,到底如何给空dataframe对象增加一列呢?其实很简单,按照如下的方式做即可。

import pandas as pd

df = pd.DataFrame()
print(df)
print('============')
df['A'] = [1]
print(df)
Empty DataFrame
Columns: []
Index: []
============
   A
0  1

很赞哦!

python编程网提示:转载请注明来源www.python66.com。
有宝贵意见可添加站长微信(底部),获取技术资料请到公众号(底部)。同行交流请加群 python学习会

文章评论

    pandas空dataframe对象添加列cannot set a frame with no defined index and a scalar文章写得不错,值得赞赏

站点信息

  • 网站程序:Laravel
  • 客服微信:a772483200