栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

python:使用.iterrows()创建列

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python:使用.iterrows()创建列

您不能使用变异的DF

row
此处添加新列,你要么是指原来的DF或使用
.loc
.iloc
.ix
,例如:

In [29]:df = pd.Dataframe(columns=list('abc'), data = np.random.randn(5,3))dfOut[29]:          a         b         c0 -1.525011  0.778190 -1.0103911  0.619824  0.790439 -0.6925682  1.272323  1.620728  0.1921693  0.193523  0.070921  1.0675444  0.057110 -1.007442  1.706704In [30]:for index,row in df.iterrows():    df.loc[index,'d'] = np.random.randint(0, 10)dfOut[30]:          a         b         c  d0 -1.525011  0.778190 -1.010391  91  0.619824  0.790439 -0.692568  92  1.272323  1.620728  0.192169  13  0.193523  0.070921  1.067544  04  0.057110 -1.007442  1.706704  9

您可以修改现有行:

In [31]:# reset the df by slicingdf = df[list('abc')]for index,row in df.iterrows():    row['b'] = np.random.randint(0, 10)dfOut[31]:          a  b         c0 -1.525011  8 -1.0103911  0.619824  2 -0.6925682  1.272323  8  0.1921693  0.193523  2  1.0675444  0.057110  3  1.706704

但是,使用row添加新列将行不通:

In [35]:df = df[list('abc')]for index,row in df.iterrows():    row['d'] = np.random.randint(0,10)dfOut[35]:          a  b         c0 -1.525011  8 -1.0103911  0.619824  2 -0.6925682  1.272323  8  0.1921693  0.193523  2  1.0675444  0.057110  3  1.706704


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/660851.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号