【问题标题】:Find and replace in pandas?在熊猫中查找和替换?
【发布时间】:2018-03-29 19:02:29
【问题描述】:

我正在对包含数字列的数据框执行 min-max-scaler 操作,但如果在这些数字列中,如果任何单元格包含字符串或空值,那么我会遇到异常。 为了避免这种情况,我想将字符串或空单元格转换为 0。 如何执行? 我的功能:

def min_max_scaler(df_sub,col_names):
"""
import the following:
from sklearn import preprocessing
from sklearn.preprocessing import StandardScaler

df_sub    : Expecting a subset of data frame in which every columns should be number fields
        (It contains all the columns on which you want to perform the operation)
example   : df_subset = df.filter(['latitude','longitude','order.id'], axis=1)
col_names : All column names of the subset
"""
    scaler = preprocessing.MinMaxScaler()
    scaled_df = scaler.fit_transform(df_sub)
    scaled_df = pd.DataFrame(scaled_df, columns=col_names)

    return scaled_df

数据集:

day phone_calls received
7       180      NaN
8       8        NaN
9     -240       qbb

如何在执行此功能之前进行验证。请帮助。

【问题讨论】:

    标签: python pandas scikit-learn


    【解决方案1】:

    我会这样做:

    查找object dtype 的列:

    obj_cols = df[col_names].columns[df[col_names].dtypes.eq('object')]
    

    将它们转换为数字 dtype,将 NaN 替换为 0(零):

    df[obj_cols] = df[obj_cols].apply(pd.to_numeric, errors='coerce').fillna(0)
    

    规模:

    df[obj_cols] = scaler.fit_transform(df[obj_cols])
    

    作为一个函数:

    def min_max_scaler(df_sub,col_names):
        scaler = preprocessing.MinMaxScaler()
        obj_cols = df_sub[col_names].columns[df_sub[col_names].dtypes.eq('object')]
        df_sub[obj_cols] = df_sub[obj_cols].apply(pd.to_numeric, errors='coerce').fillna(0)
    
        return df_sub
    

    【讨论】:

    • 如果它包含“字符串”值,那么如何用 0 替换它?
    • @Sidhartha,它已经被 .apply(pd.to_numeric, errors='coerce').fillna(0) 覆盖了——它将字符串转换为 NaN,.fillna(0) 将用零替换 NaN
    • 我已经更新了问题,我需要将这三行添加到函数的第一行吗?
    猜你喜欢
    • 2022-06-22
    • 1970-01-01
    • 2023-03-06
    • 2019-02-22
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    • 2013-04-15
    • 2015-09-13
    相关资源
    最近更新 更多