在数据框中删除一行[具有文本而不是数字[可能很容易](Pandas、数据框、python)

2024-05-29 07:33:46 发布

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

假设我有一个数据帧:

>>> df = pd.DataFrame({'num legs': [2, 4, 0, Infinity], 'num wings': [2, 0, NHN, 5], 'num arms': [2, 0, NHN, 5]})
....

>>> df
num legs  num wings  num arms
       2          2         6
       4          0         4
       0        NHN         1
Infinity          5         0

如何让它在列中查找非文本并删除该行。假设我想删除带有NHN和无穷大的行,因为它包含文本,而它应该是数值

我想做一些类似的事情: df = df[~df['num legs','num wings', 'num arms'].isin(['NHN, Infinity'])]

但是我的数据集有80列,其中2列的值中应该有文本,78列应该是数字

我该怎么做呢


Tags: 数据文本dataframedf数字事情num数值
3条回答

您可以获取所有字段均为int的行:

pd.DataFrame([df.iloc[i] for i in range(len(df)) if type(df['num wings'][i]) is int and type(df['num legs'][i]) is int and type(df['num arms'][i]) is int])

首先指定数字列:

cols = ['num legs','num wings', 'num arms']

或指定的非数字列,用于数字^{}

exclude = ['non numeric1','non numeric1']
cols = df.columns.difference(exclude)

然后通过^{}将非数值转换为NaN,最后通过^{}删除带有它们的行:

df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')

#remove only NaNs rows
df = df.dropna(subset=cols)

#remove NaN, +inf and -inf rows
df = df[~df.isin([np.nan, np.inf, -np.inf]).any(axis=1)]

首先创建一个函数:-

import numpy as np

def func(val):
    if type(val)==str:
        return np.nan
    else:
        return val

现在就用这个:-

df=df.applymap(func).dropna().astype(int)

相关问题 更多 >

    热门问题