You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R中带条件sapply的Python等效实现:移除数据框逻辑列

Converting R's sapply Logic to Python (Pandas)

First, let's recap what your original R code does:

data <- data[, sapply(data, class)!= "logical"]
This line checks the class of every column in your data frame, then retains only the columns that aren't of type logical.

In Python, if you're using pandas (the standard library for tabular data frames), there are a couple of clean, idiomatic ways to replicate this behavior:

Method 1: Use select_dtypes (Simplest Approach)

Pandas has a built-in method select_dtypes that lets you include or exclude specific data types directly. Since logical/boolean columns in pandas have the dtype bool, we can exclude them in one concise line:

import pandas as pd

# Sample data matching your example
data = pd.DataFrame({
    'Name': ['V', 'P', 'S', 'H'],
    'Designation': ['Data Scientist', 'Data Scientist', 'Senior Data Analyst', 'Senior Data Analyst'],
    'YrofExp': [15, 10, 6, 8],
    'IsActive': [True, True, False, False]  # This is the boolean/logical column
})

# Remove all boolean columns
filtered_data = data.select_dtypes(exclude=['bool'])

Method 2: Mimic the sapply Iteration (More Explicit)

If you want to mirror the R code's approach of checking each column's type explicitly, you can iterate over the columns, filter out boolean ones, then subset the data frame:

# Get a list of columns that are NOT boolean
non_bool_columns = [col for col in data.columns if data[col].dtype != 'bool']

# Subset the data frame to keep only those columns
filtered_data = data[non_bool_columns]

Both methods will produce the same result: a data frame without any boolean/logical columns. For your sample data, this means you'll retain the Name, Designation, and YrofExp columns.

内容的提问来源于stack exchange,提问作者Shuvayan Das

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:25:44