Python Forum
How to keep leading zeros with pandas?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to keep leading zeros with pandas?
#1
I have a csv file with 4 columns.
col 1 (numbers)
col 2 (text)
col 3 (numbers)
col 4 (text)

technically all four columns have a format type of general, basically my number are not really numbers which is fine.

When I import into pandas it removes my leading zeros for ONLY 3 (col 1 loads fine for some reason). How can I keep the leading zeros for col 3? I guess I have to tell pandas to treat those columns as strings?
df = pd.read_csv("myfile.csv")
*I am new to python
Reply
#2
You can specify the column types instead of letting the read_csv file guess.

dtype
Type name or dict of column -> type, optional
Data type for data or columns. E.g. {‘a’: np.float64, ‘b’: np.int32, ‘c’: ‘Int64’} Use str or object together with suitable na values settings to preserve and not interpret dtype. If converters are specified, they will be applied INSTEAD of dtype conversion.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Removing leading whitespaces palladium 1 730 Mar-24-2023, 04:15 PM
Last Post: bowlofred
  Removing leading\trailing spaces azizrasul 8 2,721 Oct-23-2022, 11:06 PM
Last Post: azizrasul
  How to retrieve records in a DataFrame (Python/Pandas) that contains leading or trail mmunozjr 3 1,765 Sep-05-2022, 11:56 AM
Last Post: Pedroski55
  -i option changes sys.path (removes leading empty string '') markanth 6 1,993 Aug-26-2022, 09:27 PM
Last Post: markanth
  remove zeros at the end of a number Frankduc 7 2,177 Feb-25-2022, 03:48 PM
Last Post: Frankduc
  Solving for zeros of an equation! fmitchell17 0 1,837 Apr-05-2021, 07:49 PM
Last Post: fmitchell17
  Dataframe Removes Zeros JoeDainton123 2 4,402 Sep-17-2020, 12:47 PM
Last Post: scidam
  Cancelling 'open directory' leading to crash Fairbz_ 1 2,189 May-08-2020, 03:14 PM
Last Post: DPaul
  leading zero number formatting RedSkeleton007 3 3,943 Jan-27-2019, 04:56 PM
Last Post: RedSkeleton007
  Probs with leading zeros falling away :-) Badosc 2 2,884 Dec-04-2018, 08:57 PM
Last Post: Badosc

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020