删除条件在数据帧中给出true或false的行

2024-10-01 19:28:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个使用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")

我有一个名为“Number”的列:

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中的行不会被删除。。。我能做些什么来解决这个问题


Tags: columnstofalsetrueobjnumberpandasdf
1条回答
网友
1楼 · 发布于 2024-10-01 19:28:14
S = ['S']
cond=df['Number'].str.startswith(tuple(S))

在上面的代码之后,只需使用~(按位求反运算符)将布尔掩码(cond)传递给数据帧:

df=df[~cond]

最后:

df.to_excel("incidencias.xlsx")

相关问题 更多 >

    热门问题