I followed the following procedure: In Python, how do I convert all of the items in a list to floats? because each column of my Dataframe is list
, but instead of floats
I chose to change all the values to strings
.
df = [str(i) for i in df]
But this failed.
It simply erased all the data except for the first row of column names.
Then, trying df = [str(i) for i in df.values]
resulted in changing the entire Dataframe into one big list, but that messes up the data too much to be able to meet the goal of my script which is to export the Dataframe to my Oracle table.
Is there a way to convert all the items that are in my Dataframe that are NOT strings into strings?
You can convert the column “Fee” to a string by simply using DataFrame. apply(str) , for example df["Fee"]=df["Fee"]. apply(str) .
Pandas series can be converted to a list using tolist() or type casting method. There can be situations when you want to perform operations on a list instead of a pandas object. In such cases, you can store the DataFrame columns in a list and perform the required operations.
To convert Pandas DataFrame to List in Python, use the DataFrame. values(). tolist() function.
You can use this:
df = df.astype(str)
out of curiosity I decided to see if there is any difference in efficiency between the accepted solution and mine.
The results are below:
example df:
df = pd.DataFrame([list(range(1000))], index=[0])
test df.astype
:
%timeit df.astype(str) >> 100 loops, best of 3: 2.18 ms per loop
test df.applymap
:
%timeit df.applymap(str) 1 loops, best of 3: 245 ms per loop
It seems df.astype
is quite a lot faster :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With