从pandas数据帧中删除不是整数且在指定数值范围之外的列

2024-03-29 01:44:04 发布

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

导入了数据帧的数据。但是,导入的数据可能不正确,因此我正在尝试删除它。示例数据帧:

    user    test1    test2    other
0   foo       1        7       bar
1   foo       2        9       bar
2   foo       3;as     5       bar
3   foo       3        5       bar

我想要清理列test1test2。我想删除不在指定范围内的值以及那些包含字符串的值(如上面的条目3;as)所示。我通过定义一个可接受的值来做到这一点:

^{pr2}$

我想清理一下名单:

headers = ['test1', 'test2']

我现在的代码是:

# Remove string entries
for i in headers:
    df[i] = pd.to_numeric(df[i], errors='coerce')
    df[i] = df[i].fillna(0).astype(int)

# Remove unwanted values
for i in values_dict:
    df[i] = df[df[i].isin(values_dict[i])]

但是,错误的值似乎没有被删除,以形成所需的数据帧:

    user    test1    test2    other
0   foo       1        7       bar
1   foo       3        5       bar

谢谢你的帮助!在


Tags: 数据indfforfooasbardict
1条回答
网友
1楼 · 发布于 2024-03-29 01:44:04

您可以这样做;使用np.logical_and从多个列构造and条件,并使用它对数据帧进行子集:

headers = ['test1', 'test2']
df[pd.np.logical_and(*(pd.to_numeric(df[col], errors='coerce').isin(values_dict[col]) for col in headers))]

#  user  test1  test2   other
#0  foo      1      7     bar
#3  foo      3      5     bar

分解

^{pr2}$

首先将感兴趣的列转换为数字类型,然后检查该列是否在特定范围内;这将为每个列生成一个布尔序列:

#[0     True
# 1     True
# 2    False
# 3     True
# Name: test1, dtype: bool, 
# 0     True
# 1    False
# 2     True
# 3     True
# Name: test2, dtype: bool]

为了同时满足来自所有列的条件,我们需要一个and操作,可以使用numpy.logical_and进一步构造该操作;在这里使用*将所有列条件作为参数解压。在

相关问题 更多 >