简体   繁体   中英

Check if Column Has String Object Then Convert to Numeric

I need to check if a column in my dataframe is of type 'object' and then based on that information, change all the values in that column to an integer. Here is the function I wrote to do that:

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

NOTE: The self.columns_to_index() is a function in the program that maps each column name to an index and it is not important information to answer the question.

When I run this function, I get the error:

AttributeError: 'str' object has no attribute 'multiply

Demonstrating that the conversion from a string to an integer did not work.

Here my solution:

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

or if you have a function fc to execute

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM