[英]Using Pandas in python, how do I change a certain row?
我正在努力更改 pandas 內一行內的值。
我將包含 my.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
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,並得到以下結果。
if localList.iloc[0, 2] > 0:
print("Taking seat")
localList.iloc[0, 2] = localList.iloc[0, 2] - 1
print(localList.iloc[0, 2])
SettingWithCopyWarning:試圖在 DataFrame 的切片副本上設置值。 嘗試改用 .loc[row_indexer,col_indexer] = value
請參閱文檔中的警告: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy self.obj[item] = s
在我看到之后,我多次按下購買按鈕,但它總是停留在之前的數據 - 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: 無法使用 class 'int' 的這些索引器 [2] 對 label 進行索引
然后,我想將其限制為一個變量,以測試我是否甚至可以使用 LOC 觸摸這些數據,這似乎是我做不到的。
localList.loc[0, 2] -= 1
TypeError: 無法使用 class 'int' 的這些索引器 [2] 對 label 進行索引
從這里我想看看我使用 LOC 而不是 ILOC 的工作。 所以我只是將數據打印出來。 它與 ILOC 沒有什么不同,那么為什么我不能以同樣的方式訪問這些數據呢?
print(localList.loc[0])
第 101 條
價格 50
座位 150
類型 matinee
名稱:0,數據類型:object
所以我不認為保存切片會阻止它更新 dataframe。 因此,在測試時,我發現我需要獲取我的 localList 並將其保存回最初選擇它的框架中。
編輯:我現在明白了這個問題。 您正在嘗試更新原始 dataframe matineeSeats.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
要直接更新matineeSeats_df
,您可以這樣做:
matineeSeats_df.loc[matineeSeats_df['section'] == 101, 'seats'] -= 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.