簡體   English   中英

根據列值刪除數據框行

[英]Delete dataframe rows based on column values

我創建了基於網站( https://thispointer.com/python-pandas-how-to-drop-rows-in-dataframe-by-conditions-on-column-values/ )的代碼來刪除數據中的行基於列值的框架。 'zone_type' 列可以有 5 個值之一(response_button_text、response_button_image、fixation、timelimit_screen 或 continue_button)。 除非該行的值為“response_button_image”,否則我想從數據框中刪除該行。

# select all of the rows that are not to do with the task i.e. fixation screens etc.

indexZoneType = df[ (df['zone_type'] == 'fixation') & (df['zone_type'] == 'response_button_text') & (df['zone_type'] == 'timelimit_screen') & (df['zone_type'] == 'continue_button')].index

# delete these rows

df.drop(indexZoneType , inplace=True)

我認為這段代碼應該可以工作? 並且我沒有收到錯誤,但是在執行print(df) ,數據框沒有改變。

謝謝。

好的,所以您的條件是互斥的,您可能想在那里使用“或”,即

indexZoneType = df[ (df['zone_type'] == 'fixation') |(df['zone_type'] == 'response_button_text') | (df['zone_type'] == 'timelimit_screen') | (df['zone_type'] == 'continue_button')].index

甚至更好 - 使用df.isin(...)df.loc[...]

indexZoneType = df.loc[df['zone_type'].isin(['fixation', 'response_button_text', 'timelimit_screen', 'continue_button'])].index

或者更簡單:

indexZoneType = df.index[df['zone_type'].isin(['fixation', 'response_button_text', 'timelimit_screen', 'continue_button'])]

參考: https : //pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.isin.html https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas .DataFrame.loc.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM