DataFrame changing the DataType by using "astype"

2392 views python

I got the following problem:

I have a Dataframe, where i would like to set the decimals to a fixed width, and if i change the "columnstyle" by using "apply{}" it works perfectly, but if i export this dataframe as a *.txt i become an error with an other program, where i would like to import this Dataset. If i do the change via *.astype(float) the programm is able to import the Dataset, but get problemes with the tabulators and the size of each value.

enter image description here

Is there a way to set each value to a fixed size by using *.astype()?

For Example the Column "F [HZ]" Should look like: 30.00, 10.78, 10.90

Thanks for Help!

answered question

1 Answer


I guess you are using pd.to_csv to save it as a text file. In this you can use it as below to save the floating numbers with a fixed width:

df = pd.DataFrame({'F[HZ]': [30, 10.78, 10.9025], 'T[C]':[-50, -50, -50]})
df.to_csv('outfile.txt', float_format='%.2f')

I hope this helps you.

posted this

Have an answer?


Please login first before posting an answer.