检查列是否具有字符串对象,然后转换为数字

时间:2019-03-04 01:35:23

标签: python pandas dataframe

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

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

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

1 个答案:

答案 0 :(得分:0)

这是我的解决方案:

#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)