Exporting to csv from python dataframe

Viewed 25

I have a dataset consists of Id and mobile no e.g

Id. Mob_no

  1. nan
  2. 123456789
  3. 213465789

I am trying to exporting dataset in csv from python dataframe. Then additional leading zeros is created in Mob_no column e.g

Id. Mob_no

  1. nan
  2. 123456789.000
  3. 213465789.000

How should I export to keep the mob_no same

2 Answers

Suggest dropping na_values and converting to int:

import pandas as pd
columns = ['Id', 'Mob_no']
data = [(1, None), (2, 123456789), (3, 213465789)]
df = pd.DataFrame(data, columns=columns)
df.dropna(inplace=True)
df.iloc[:, -1] = df.iloc[:, -1].astype(int)
df.to_csv('path/to/destination/sample.csv', index=False)
print(df)
   Id     Mob_no
1   2  123456789
2   3  213465789
df = pd.read_csv('path/to/destination/sample.csv')
print(df)
   Id     Mob_no
0   2  123456789
1   3  213465789

Would that work for your purpose?

just pass the float_format argument as shown below:

df.to_csv('path/to/destination/sample.csv',float_format='%.3f')
Related