在python中使用Pandas,如何更改某一行?
我正在修改pandas中一行的值 我将包括我的.csv文件的前两行,这样您就可以对数据有一个感觉在python中使用Pandas,如何更改某一行?,python,pandas,Python,Pandas,我正在修改pandas中一行的值 我将包括我的.csv文件的前两行,这样您就可以对数据有一个感觉 section,price,seats,type 101,50.00,150,matinee 正如你所看到的,这是非常直截了当的。问题就在这里 localList = matineeSeats.df.loc[matineeSeats.df['section'] == int(selection)] #Create slice of DataFrame for selected section
section,price,seats,type
101,50.00,150,matinee
正如你所看到的,这是非常直截了当的。问题就在这里
localList = matineeSeats.df.loc[matineeSeats.df['section'] == int(selection)] #Create slice of DataFrame for selected section
if localList.iloc[0, 2] > 0: #If theres more than 0 seats left... Cant do [0, 'seats']
print("Taking seat")
#Set the seats -= 1 ###THIS LINE###
注意:由于某些原因,我无法通过执行localList.iloc['seats']访问数据,但可能我做得不对
我试过的 我不知道如何使座位每次购买一张时减少1张。“这条线”是我所有问题的根源。我试着把这个值设置为等于它本身减去1,得到了如下结果 试试1 SettingWithCopyWarning:正在尝试在副本上设置值 从数据帧切片。尝试使用.loc[行索引器、列索引器]= 取而代之的是价值观 请参阅文档中的注意事项: self.obj[item]=s 试试2 在我看到这一点后,我多次按下“购买”按钮,但它始终保持在以前的数据-1,并且不会再进一步递减。所以我试了一下控制台里给我的东西。使用LOC代替ILOC
if localList.iloc[0, 2] > 0:
print("Taking seat")
localList.loc[0, 2] = localList.loc[0, 2] - 1
print(localList.iloc[0, 2])
TypeError:无法使用“int”类的这些索引器[2]对进行标签索引
试试3
然后我想把它限制为一个变量,以测试我是否可以用LOC来触摸这些数据,这似乎是我做不到的
localList.loc[0, 2] -= 1
TypeError:无法使用“int”类的这些索引器[2]对进行标签索引
试试4
从这里,我想看看我使用LOC而不是ILOC做了些什么。所以我只是把数据打印出来。它与ILOC没有什么不同,那么为什么我不能以相同的方式访问这些数据呢
print(localList.loc[0])
第101节
价格50
150个座位
日场
名称:0,数据类型:对象
是什么帮我修好的
所以我不认为保存切片会阻止它更新数据帧。因此,在测试时,我发现我需要将我的localList保存回最初选中的框架中。编辑:我现在理解了这个问题。您正在尝试更新原始数据帧
日场座位.df
而不是localList
问题
您正在使用.loc
选项创建副本
import pandas as pd
matineeSeats_df = pd.DataFrame([{'section': 101, 'price': 50.0, 'seats': 150, 'type': 'matinee'}])
# this creates a copy
localList = matineeSeats_df.loc[matineeSeats_df['section'] == 101]
# just localList gets updated, matineeSeats_df is not updated
localList.at[0, 'seats'] = localList.at[0, 'seats'] - 1
解决方案
要直接更新日场座椅\u df
,您可以这样做:
matineeSeats_df.loc[matineeSeats_df['section'] == 101, 'seats'] -= 1
这给了我与Try 1中相同的问题。它改变了一次,然后再也不会改变了。我更新了答案。使用该解决方案直接更新原始数据帧
matineeSeats_df.loc[matineeSeats_df['section'] == 101, 'seats'] -= 1