Pandas:如何删除列值包含数字的行?

ijnw1ujt  于 2023-03-11  发布在  其他
关注(0)|答案(2)|浏览(156)

我试图删除特定列值为数字的行。以下是我的尝试-

# Import pandas library
import pandas as pd

# initialize list of lists
data = [['tom', 'Ten'], ['nick', 'Fifteen'], ['juli', 14]]

# Create the pandas DataFrame
df = pd.DataFrame(data, columns=['Name', 'Age'])
#https://stackoverflow.com/questions/48996822/python-drop-rows-from-a-pandas-dataframe-that-contain-numbers
df = df[~df.Age.str.contains(r'\d')]

# print dataframe.
print(df)

在本例中,应该删除Age = 14的行,但我得到了以下错误-

TypeError: bad operand type for unary ~: 'float'

编辑1:我非常感谢所有的快速回答。但不幸的是,我的尝试没有涵盖一个边缘情况。如果数据是这样的格式-

data = [['tom', 'Ten'], ['nick', 'Fifteen'], ['juli', '4chan'], ['astha', 18]]

在这里,我查找要删除的Age = 18的行,而不是Age = 4chan的行

sqxo8psd

sqxo8psd1#

Age列强制转换为str类型,并使用str.isnumeric检查字符串是否为数字:

df[~df.Age.astype(str).str.isnumeric()]
Name      Age
0   tom      Ten
1  nick  Fifteen
1l5u6lss

1l5u6lss2#

您需要将其转换为str 1st

out = df[~df.astype(str).Age.str.contains(r'\d')]
Out[22]: 
   Name      Age
0   tom      Ten
1  nick  Fifteen

相关问题