我正在尝试使用while循环在“ list1”和“ list2”的行中添加元素。但是得到"KeyError: 'the label [7] is not in the [index]"
。我知道执行此操作的简单方法是:
df['sum'] = (df["list1"]+df["list2"])
但出于学习目的,我想尝试使用循环。
import pandas as pd
df= pd.DataFrame({"list1":[2,5,4,8,4,7,8],"list2":[5,8,4,8,7,5,5],"list3":
[50,65,4,82,89,90,76]})
d=[]
count=0
x=0
while count<len(df):
df1=df.loc[x,"list1"]+df.loc[x,"list2"]
d.append(df1)
x=x+1
count=count+1
df["sum"]=d
答案 0 :(得分:0)
您真的很亲近,但只有几点建议:
不需要count
和x
这两个值
您收到错误消息是因为df(7)的len超出了loc
所寻找的索引。可以通过执行len(df)-1
您不需要x = x+1
就可以使用x+=1
d=[]
x=0
while x <= len(df)-1:
df1 = df.loc[x, "list1"] + df.loc[x,"list2"]
d.append(df1)
x += 1
df["sum"]=d