Python:将自定义函数应用于数据框中的多个指定列

标签 python pandas dataframe

我创建了一个函数,用于查找数据框中缺失的值。 缺失值在我们的数据集中可以采取多种形式,下面的这个玩具函数可以处理它 我的问题是关于应用这个函数。 我有一个列列表(20 左右),我想对其应用相同的函数。 以下是一列的设置


import numpy as np
import pandas as pd
from sklearn.datasets import load_iris

# Create a sample dataset
iris = load_iris()

df = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
                 columns= iris['feature_names'] + ['target'])
df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)

# Here we replace all values of setosa with 'missing_value'
df = df.applymap(lambda x: 'missing_value' if x == 'setosa' else x)

# Here we want to create a flag for the missing values
def add_missing_value_flags(mydf, column):
    
    # Generate the new column name
    new_col = "missing_" + column
    
    # Create flags where the data is missing
    # that has put in a holder to represent a missing value
    mydf[new_col]= np.where(mydf[column] == 'missing_value', True,
                            np.where(mydf[column] == '', True,
                            np.where(mydf[column] == 'N/A', True,  
                            np.where(mydf[column] == 'N\A', True, 
                            np.where(mydf[column] == 'NA', True,
                            np.where(mydf[column] == 'N.A.', True,
                            np.where(mydf[column] == 'NONE', True,
                            np.where(mydf[column] == '.', True, 
                            np.where(mydf[column].str.len() == 1, True, 
                            np.where(mydf[column] == '..', True, False))))))))))
    
    return(mydf)


add_missing_value_flags(df, 'species')

     sepal length (cm)  sepal width (cm)  ...        species  missing_species
0                  5.1               3.5  ...  missing_value             True
1                  4.9               3.0  ...  missing_value             True
2                  4.7               3.2  ...  missing_value             True
3                  4.6               3.1  ...  missing_value             True
4                  5.0               3.6  ...  missing_value             True
..                 ...               ...  ...            ...              ...
145                6.7               3.0  ...      virginica            False
146                6.3               2.5  ...      virginica            False
147                6.5               3.0  ...      virginica            False
148                6.2               3.4  ...      virginica            False
149                5.9               3.0  ...      virginica            False

Python中是否有一种方法可以将我的函数应用于我的其余列​​,类似于: mydf[mydf.columns[mydf.columns.str.contains('species |植物|地球')]].应用...

最佳答案

# Create a sample dataset
iris = load_iris()

df = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
                 columns= iris['feature_names'] + ['target'])
df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)

# Here we replace all values of setosa with 'missing_value'
df = df.applymap(lambda x: 'missing_value' if x == 'setosa' else x)


def function_to_apply(series):
    if not re.match("missing_", series.name):
        new_column_name = "missing_"+series.name
        new_column_values = series.isin([
            'missing_value', '', 'N/A', 'N\A',
            'NA', 'N.A.', 'NONE', '.', '..'
        ])
        try:
            new_column_values = new_column_values | (series.str.len()==1)
        except AttributeError:
            pass
        df[new_column_name] = new_column_values
    return

我编写了 function_to_apply 以便就地修改 df 并设置返回值 = None,因此:

df.apply(function_to_apply)
#RETURNS
#sepal length (cm)    None
#sepal width (cm)     None
#petal length (cm)    None
#petal width (cm)     None
#target               None
#species              None
#dtype: object

但是,通过应用此函数,您已向 df 添加了列: modified df

我知道这不是最干净的解决方案,但它有效并且相对较快。

附注除了其他库之外,您还需要导入 re 才能运行此代码。

关于Python:将自定义函数应用于数据框中的多个指定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73063204/

相关文章:

python - 将 Pandas DataFrame 与不同列中的键合并

python - 空格分隔的 csv,列名和值中有空格

python - 将 dict 的 pandas dataframe 列扩展为 dataframe 列

python - 如何将数组转换为数据框?

python - 可在当前命名空间中转储的可挑选数据容器

python - Python 中的 filter、map 和 reduce 是否创建列表的新副本?

python - 如何获取日期时间所在的期初和期末日期时间值?

r - 将 R 数据帧拆分为 n 个因子

python - 在两个应用程序之间使用 url_for

python - 捕获未写入 stdout、stderr 的控制台输出?