[英]How to remove rows in a Pandas Dataframe with a specific column containing numbers only?
Lets say I have this DF: 让我们说我有这个DF:
ID IGName Date_created
0 BananaMan 09/10/2018
1 Superman247 10/10/2009
2 123456789 08/03/2011
3 Nameless101 07/12/2012
I want to be able to remove all the rows in the DF where the IGName
is only numbers. 我希望能够以去除 DF当所有行IGName
只是数字。
Like how in this example, row 3 is all numbers. 就像在这个例子中,第3行是所有数字。 I want to be able to keep the names alphanumeric rows but not the rows with ONLY numerics. 我希望能够保留名称字母数字行,但不能保留只有数字的行。
I want the result to look like this: 我希望结果看起来像这样:
ID IGName Date_created
0 BananaMan 09/10/2018
1 Superman247 10/10/2009
3 Nameless101 07/12/2012
You could do: 你可以这样做:
import pandas as pd
data = [[0, 'BananaMan', '09/10/2018'],
[1, 'Superman247', '10/10/2009'],
[2, '123456789', '08/03/2011'],
[3, 'Nameless101', '07/12/2012']]
df = pd.DataFrame(data=data, columns=['ID', 'IGName', 'Date_created'])
df = df[~df['IGName'].str.isnumeric()]
print(df)
Output 产量
ID IGName Date_created
0 0 BananaMan 09/10/2018
1 1 Superman247 10/10/2009
3 3 Nameless101 07/12/2012
From the documentation : 从文档 :
Check whether all characters in each string in the Series/Index are numeric. 检查Series / Index中每个字符串中的所有字符是否都是数字。 Equivalent to str.isnumeric(). 相当于str.isnumeric()。
Note that this solution assumes the column 'IGName'
is of type string, otherwise you need to cast it to string, doing something like (as mentioned by @RafaelC): 请注意,此解决方案假定列'IGName'
的类型为字符串,否则您需要将其强制转换为字符串,执行类似(如@RafaelC所述):
df['IGName'] = df['IGName'].astype(str)
Use df[...]
: 使用df[...]
:
print(df[~df['IGName'].str.isnumeric()])
Or: 要么:
print(df[df['IGName'].str.contains(r'\D+')])
Both Output: 两个输出:
ID IGName Date_created
0 0 BananaMan 09/10/2018
1 1 Superman247 10/10/2009
3 3 Nameless101 07/12/2012
If IGName
has integers do: 如果IGName
有整数,请执行以下操作:
print(df[pd.to_numeric(df.IGName, errors='coerce').notnull()])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.