Python Pandas:删除列值包含字母或符号的行

2024-09-24 02:17:38 发布

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

如何删除“配方开始”或“配方结束”列包含字母/符号的行?公司名称:

    Title Recipe Start Recipe End  Year
0  cookie       500        400     2013
1    soup       600        650     1993
2    rice        30      5A-EE     1810
3   ramen         v        vii     2001
4    pate      EP56        2KP     2005 

输出:

^{pr2}$

我所做的:

import pandas as pd
import re
raw = {'Title': ['cookie', 'soup', 'rice', 'ramen', 'pate'], 
    'Recipe Start': [500, 600, 30, 'v', 'EP56'], 
    'Recipe End': [400, 650, '5A-EE', 'vii', '2KP'],
    'Year': [2013, 1993, 1810, 2001, 2005]}
data = pd.DataFrame(raw, columns = ['Title', 'Recipe Start', 'Recipe End', 'Year'])
data['Recipe Start'] = data[[(re.search(r'[a-zA-Z]', x)==False) for x in data['Recipe Start'].astype(str)]]
print(data)

Tags: datatitlecookie配方recipeyearstartee
2条回答

选项1
^基于{}的过滤

df[df.iloc[:, 1:3].apply(pd.to_numeric, errors='coerce').notnull().all(1)]

    Title Recipe Start Recipe End  Year
0  cookie          500        400  2013
1    soup          600        650  1993

选项2
str.isdigit

^{pr2}$

如果这些是对象列,则需要事先转换为str,然后可以对这些列使用str访问器方法:

i = df['Recipe Start'].astype(str).str.isdigit()
j = df['Recipe End'].astype(str).str.isdigit()

df[i & j]

选项3
applymap+str.isdigit

df[df.iloc[:, 1:3].astype(str).applymap(str.isdigit).all(1)]

    Title Recipe Start Recipe End  Year
0  cookie          500        400  2013
1    soup          600        650  1993

{cda>你可以用这个来代替

data.loc[data[['Recipe Start','Recipe End']].replace('[A-Za-z]',np.nan,regex=True).dropna().index]

    Title Recipe Start Recipe End  Year
0  cookie          500        400  2013
1    soup          600        650  1993

相关问题 更多 >