我正在使用pandas从csv和excel文件导入一些数据,它们现在是dataframe类型。我正在尝试使用csv来更新excel文件中的数据。我已经正确地读取了数据,但是当我尝试遍历数据以查找某个键是否已经存在时,if语句不起作用。
for ID in update['Index']:
if ID not in data['index']:df1:数据
Index Attr-1 Attr-2 Attr-3
01234 Blue Car Water
23456 Green Truck Lemonade
34567 Red Bike Milk Teadf2:更新
Index Attr-1 Attr-2 Attr-3
01234 Blue Car Milk Tea
34567 Yellow Truck Lemonade
56789 Red Bike Milk Tea实际结果:
Index Attr-1 Attr-2 Attr-3
01234 Blue Car Milk Tea
01234 Blue Car Water
23456 Green Truck Lemonade
23456 Green Truck Lemonade
34567 Red Bike Milk Tea
34567 Yellow Truck Lemonade
56789 Red Bike Milk Tea期望的结果:
Index Attr-1 Attr-2 Attr-3
01234 Blue Car Milk Tea
23456 Green Truck Lemonade
34567 Yellow Truck Lemonade
56789 Red Bike Milk Tea我的值被复制了,因为if语句没有捕获这些值。不太确定是怎么回事?任何反馈/想法都值得感谢。谢谢。
发布于 2019-06-19 00:00:42
请查看是否有效,您需要检查索引中的ID:
>>> data = pd.DataFrame({'Attr-1':['Blue','Green','Red']},index=['01234','23456','34567'])
>>> update = pd.DataFrame({'Attr-1':['Blue','Yellow','Green']},index=['01234','34567','56789'])
>>> for ID in update.index:
... if ID not in data.index:
... data = data.append(update.loc[ID])
...
>>> data
Attr-1
01234 Blue
23456 Green
34567 Red
56789 Green发布于 2019-06-19 04:55:48
数据帧不是我被允许使用"in“on的东西,这就是为什么我的for循环没有传递,所以我创建了一个数组来保存键,data‘’index‘。
`s = data['index'].tolist()
for ID in update['index']:
if ID not in s:`https://stackoverflow.com/questions/56652878
复制相似问题