3

I am struggling to understand why am I getting \n1 and \n2 outputs after converting int64 to str.

From year 2014 to 0 2014\n1 2015\n2 2015\n3 2016.

This is what I did: df.Year = str(df.Year)

Before:

enter image description here

After:

enter image description here

Close-up:

enter image description here

martineau
  • 119,623
  • 25
  • 170
  • 301
Icemilo
  • 53
  • 5

2 Answers2

6

When you’re using str(do.Year) you get a string representation of all the rows, not a Series with each row as a string. To convert the rows to strings, you need to use df.Year = df.Year.astype(str)

Shahar Melamed
  • 1,534
  • 5
  • 15
  • 23
3

This might help to perform what was intended (convert a column to a specific type) Change column type in pandas. As regards to why this is happening, lets take an example

table.csv
Year
2010
2011
2012

lets consider this snippet

import pandas as pd 
df = pd.read_csv("table.csv")
print(str(df.Year))

The output produced is

0    2010
1    2011
2    2012
Name: Year, dtype: int64

As this link clearly mentions, attribute access against a dataframe returns a series object. And when you call str against a series, it basically calls Series.str (Does python `str()` function call `__str__()` function of a class?) and therefore after doing the operation mentioned in the question, you store the result of Series.str in every row of the column Year. As mentioned in the beginning of this post, you can refer to the SO link, it is pretty self explanatory. However, if you want a code sample, please comment.

Code Snippet
Here is one of the ways to convert a column to integer type(inspired from the SO link shared above)

import pandas as pd 
df = pd.read_csv("table.csv")
df.Year = df.Year.astype(str)
print(type(df.Year[0])) #Prints <class 'str'>
print(df)
punter147
  • 302
  • 2
  • 7
  • Thanks for your input. Extremely helpful for my journey to understand basics and i dont mind having a code sample if it is not too troublesome. – Icemilo Dec 20 '20 at 06:35
  • @Icemilo thank you choosing the post as the answer. Its my pleasure. As you requested, I have included a code sample inspired from a linked SO post. Regards – punter147 Dec 20 '20 at 08:43