Python Forum
Convert dataframe string column to numeric in Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Convert dataframe string column to numeric in Python
#1
Hello,
I have taken a sample data as dataframe from an url and then added columns in that. While I try to perform some calculations, I realised that column 'Dage' and 'Cat_Ind' are not numeric but string. So, how to convert them to numeric so as to do next level of analysis?

df2=pd.read_csv("http://users.stat.ufl.edu/~winner/data/agedeath.dat", header = None)
df2.columns =["col1"]
print (df2)
df3 = df2.col1.str.split(expand = True)
df3.columns = ["Cat","Dage", "Cat_Ind"]
print (df3)
Resulting dataframe is:
Output:
Cat Dage Cat_Ind 0 aris 21 1 1 aris 21 2 2 aris 21 3 3 aris 21 4 4 aris 21 5 ... ... ... ... 6181 sovr 95 1436 6182 sovr 95 1437 6183 sovr 97 1438 6184 sovr 100 1439 6185 sovr 101 1440 [6186 rows x 3 columns]
Here is the problem: I use below code -
df3['Dage'].min()
getting output as:
Output:
'100'
I suspect that this must be due to the fact that column 'Dage' is not here as the integer- but string.

Q. How to get this column converted to integer values? Please help
Reply
#2
Did you even look at the docs? read_csv takes a parameter dtype that lets you specify the types of the columns: https://pandas.pydata.org/docs/user_guid...-csv-table.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  concat 3 columns of dataframe to one column flash77 2 776 Oct-03-2023, 09:29 PM
Last Post: flash77
  HTML Decoder pandas dataframe column mbrown009 3 961 Sep-29-2023, 05:56 PM
Last Post: deanhystad
  attempt to split values from within a dataframe column mbrown009 8 2,217 Apr-10-2023, 02:06 AM
Last Post: mbrown009
  New Dataframe Column Based on Several Conditions nb1214 1 1,781 Nov-16-2021, 10:52 PM
Last Post: jefsummers
  Putting column name to dataframe, can't work. jonah88888 1 1,803 Sep-28-2021, 07:45 PM
Last Post: deanhystad
Sad ValueError: could not convert string to float badju 0 4,294 Jul-01-2021, 12:13 AM
Last Post: badju
  Setting the x-axis to a specific column in a dataframe devansing 0 1,993 May-23-2021, 12:11 AM
Last Post: devansing
  Convert several columns to int in dataframe Krayna 2 2,361 May-21-2021, 08:55 AM
Last Post: Krayna
Question [Solved] How to refer to dataframe column name based on a list lorensa74 1 2,238 May-17-2021, 07:02 AM
Last Post: lorensa74
Question Pandas - Creating additional column in dataframe from another column Azureaus 2 2,913 Jan-11-2021, 09:53 PM
Last Post: Azureaus

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020