首页 > 解决方案 > 检查列是否有字符串对象然后转换为数字

问题描述

我需要检查我的数据框中的列是否属于“对象”类型,然后根据该信息将该列中的所有值更改为整数。这是我为此编写的函数:

def multiply_by_scalar(self):
    self.columns_to_index()

    i = ask_user("What column would you like to multiply by a scalar? Please type in index:\n", int)
    m = ask_user("Type in the value of the scalar:\n", int)

    if self.df.columns[i] == np.object:
        print("{} is of type 'object'. Scalar multiplication can only be applied to dtypes of type 'numeric'.".format(self.df.columns[i]))
        c = ask_user("Would you like to convert column '{}' to type 'int'?".format(self.df.columns[i]))
        if c in yes_values:
            pd.to_numeric(self.df.columns[i])
            self.df.columns[i] = self.df.columns[i].multiply(m)
            print(self.df.columns[i])
    else:
        self.df.columns[i] = self.df.columns[i].multiply(m)
        print(self.df.columns[i])

注意:这self.columns_to_index()是程序中将每个列名映射到索引的函数,它不是回答问题的重要信息。

当我运行这个函数时,我得到了错误:

AttributeError: 'str' object has no attribute 'multiply

证明从字符串到整数的转换不起作用。

标签: pythonpandasdataframe

解决方案


这是我的解决方案:

#df.dtypes.to_dict() create a dictionary with name column as index and dtype as values

for colname, coltype in df.dtypes.to_dict().items():
    if coltype ==  'object' : df[colname] = df[colname].astype(int)

或者如果你有一个函数 fc 要执行

def fc(colname, coltype):
    #coding fc here

for colname, coltype in df.dtypes.to_dict().items():
    if coltype ==  'object' : fc(colname, coltype)

推荐阅读