python:使用.iterrows()创建列

python:使用.iterrows()创建列,第1张

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


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5666967.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存