I have an integer dataframe and in my code I am doing some length calculation( which can be only perfomred on string), therefore I need to convert my dataframe to String. I have tried using str(), its not helping me, it would be helpful if you could suggest something.

Recommended Answers

All 6 Replies

Give us an example of a dataframe.

Dataframe sample is given below:
Item Class Cd
57
57
57
57
57
57
57
57
57
57
57
18

I am reading it as
df = pd.read_csv("C:\Desktop\TEST.csv")

Apparently, you are using pandas DataFrame instances. The api reference for these objects contains conversion methods. I would try

s = df.to_string()

Thanks for the prompt reply. I will rather talk about my issue in detail.
My code is :
df1 = pd.read_csv("C:\Desktop\TEST.csv")
df=df1.to_string()
mylist=df["Item Class Cd"]

max_len=len(max(mylist, key=len))
min_len=len(min(mylist, key=len))

Item Class Cd is integer, so to perform len function on it, this needs to be converted to string.
And when I am executing the above code it is giving me error:
mylist=df["Item Class Cd"]
TypeError: string indices must be integers

After df=df1.to_string(), df is a str object (a sequence of bytes). You can use df[11] which gives you the 12th character in the sequence, but not df["Item Class Cd"].

So how do I resolve my problem in that case

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.