Home > Back-end >  Convert a integer to a String in Python Pandas
Convert a integer to a String in Python Pandas

Time:09-22

So I want to convert a single integer to string in Pandas not a whole column or row. However, Pandas won't allow me to use str(i) which i is an integer and have the error module object is not callable. How should I fix this?

So I have an index i = 5 I want to append this to a string str = '[' str(i) ']' My expectation would be str = 1 enter image description here

CodePudding user response:

you can you astype, for example, I create a dataframe:

df = pd.DataFrame({"col1":["A","B","C"],
                   "col2":[1,2,3]})
df.head()

output:

   col1 col2
0   A   1
1   B   2
2   C   3

and turn the value 3 in col2 to str:

temp = df.col2[2].astype(str)
temp, type(temp)

output:

('3', numpy.str_)

OR, The f-string can be you in your case:

str = f"something here {df.index[i]} something here"

CodePudding user response:

The whole column will turn into 'object'(which means 'string' data in this case) when you change any single one element of the numerical column into 'string'.

You can try with:

df.colA[0] = str(df.colA[0])
# Then check the column 'colA' if its dtype is 'object'
df.colA
  • Related