0
$\begingroup$

I need to find the columns in data frame, which has numeric values and are stored as string.

data_set = pd.DataFrame({"Number":["1","2","3","4","5"], "Char":["A","B","C","D","E"]})
data_set.dtypes

In above code, column "Number" has numeric values, but stored as string. I have to iterate through columns and convert it to int or float.

I can do it by taking column name and convert it.

data_set["Number"] = data_set["Number"].astype(int)

What i need is to do it dynamically. Dynamically means, iterating through columns and changing it.

$\endgroup$
  • $\begingroup$ Can you elaborate on what you mean by dynamically? $\endgroup$ – grldsndrs Jul 17 '19 at 6:05
  • $\begingroup$ @grldsndrs Dynamically means, like iterating through columns, and change type of column. $\endgroup$ – Harshith Jul 17 '19 at 6:31
  • $\begingroup$ So you just want to iterate through the columns of it dataframe? $\endgroup$ – grldsndrs Jul 17 '19 at 6:32
  • $\begingroup$ Yes, iterate through the columns of dataframe. Find the columns with numeric values, but stored as string. And convert those column type to int/float. $\endgroup$ – Harshith Jul 17 '19 at 6:33
1
$\begingroup$

I think this does what you want.

for column in data_set:
    If isinstace(data_set[column].dtypes,str)
        data_set[column]=data_set[column].astype(int)
| improve this answer | |
$\endgroup$
  • $\begingroup$ Thank you. Above code works $\endgroup$ – Harshith Jul 17 '19 at 7:01
0
$\begingroup$

I put together the following code but I don't claim it to be the best option:

for col in data_set.columns:
    for element in data_set[col]:
        if element.isdigit():
            data_set[col] = data_set[col].astype(int)

Please note, that this code will try to convert the whole column to int, if there is a single entry of an int-value stored as string. So it might return an error for mixed type columns.

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.