jekwatt / idiomatic_pandas

Tips and tricks for the most common data handling task with pandas.
0 stars 0 forks source link

Remove leading/trailing whitespaces #24

Open jekwatt opened 2 years ago

jekwatt commented 2 years ago
# 1
df1 = pd.read_csv('input1.csv')
df1['col_1'] = df1['col_1'].str.strip()

#2
modify your read_csv lines to also use [skipinitialspace=True]
df1 = pd.read_csv('input1.csv', skipinitialspace=True)

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html

# 3
pd.read_csv(..., converters={'col_1': str.strip})
# only strip leading whitespace
pd.read_csv(..., converters={'col_1': str.lstrip})