簡體   English   中英

如果特定列中的值不是 Pandas 數據框中的整數,則刪除行

[英]Drop rows if value in a specific column is not an integer in pandas dataframe

如果我有一個數據框並想刪除其中一列中的值不是整數的任何行,我該怎么做?

如果值不在 0-2 范圍內,另一種方法是刪除行,但由於我不確定如何執行其中任何一個,我希望有人可以這樣做。

這是我嘗試過的,但不知道為什么:

df = df[(df['entrytype'] != 0) | (df['entrytype'] !=1) | (df['entrytype'] != 2)].all(1)

我提出了兩種方法:

In [212]:

df = pd.DataFrame({'entrytype':[0,1,np.NaN, 'asdas',2]})
df
Out[212]:
  entrytype
0         0
1         1
2       NaN
3     asdas
4         2

如果值的范圍如您所說的那樣受限制,那么使用isin將是最快的方法:

In [216]:

df[df['entrytype'].isin([0,1,2])]
Out[216]:
  entrytype
0         0
1         1
4         2

否則我們可以轉換為 str 然后調用.isdigit()

In [215]:

df[df['entrytype'].apply(lambda x: str(x).isdigit())]
Out[215]:
  entrytype
0         0
1         1
4         2

str("-1").isdigit()False

str("-1").lstrip("-").isdigit()工作但不好。


df.loc[df['Feature'].str.match('^[+-]?\\d+$')]

對於您的問題,反向設置

df.loc[ ~(df['Feature'].str.match('^[+-]?\\d+$')) ]

我們有多種方法可以做到這一點,但我發現這種方法既簡單又高效。

快速示例

#Using drop() to delete rows based on column value
df.drop(df[df['Fee'] >= 24000].index, inplace = True)

# Remove rows
df2 = df[df.Fee >= 24000]

# If you have space in column name
# Specify column name with in single quotes
df2 = df[df['column name']]

# Using loc
df2 = df.loc[df["Fee"] >= 24000 ]

# Delect rows based on multiple column value
df2 = df[ (df['Fee'] >= 22000) & (df['Discount'] == 2300)]

# Drop rows with None/NaN
df2 = df[df.Discount.notnull()]

暫無
暫無

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

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