[英]Delete rows that the condicion gives true or false in a DataFrame
我有一個 dataframe ,我使用 sql 選擇從 excel 中提取:
sql_con_obj = SqlConnector()
sql_con_obj.connect()
cursor = sql_con_obj.con.cursor()
sql = "SELECT * FROM table"
df = pandas.read_sql_query(sql, sql_con_obj.con)
df.to_excel("incidencias.xlsx")
我有一個名為“數字”的列:
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 125 entries, 0 to 124
Data columns (total 22 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Number 125 non-null object
我將舉例說明該列的外觀:
print(df['Number'])
0 S210401
1 S210401
2 S210401
3 S210401
4 S210401
...
121 I210224
122 I210223
123 I210219
124 I210211
125 I210118
然后我過濾以字母“S”開頭的那些:
S = ['S']
cond=df['Number'].str.startswith(tuple(S))
0 True
1 True
2 True
3 True
4 True
...
121 False
122 False
123 False
124 False
125 False
我現在想要的是刪除那些是真的並留在“我”的所以我想這樣做:
df = df.drop(df[cond].index)
我打印時的結果
print(df['Number']
120 I210224
121 I210223
122 I210219
123 I210211
124 I210118
125 I210118
但問題是在 excel 中,行沒有被刪除......我該怎么做才能解決這個問題?
S = ['S']
cond=df['Number'].str.startswith(tuple(S))
在上面的代碼之后只需使用~
(按位否定運算符)將 boolean 掩碼(cond)傳遞給您的 dataframe:
df=df[~cond]
最后:
df.to_excel("incidencias.xlsx")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.