Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pandas as pd
- df = pd.DataFrame([[' a ', 10], [' c ', 5]])
- df.replace('^s+', '', regex=True, inplace=True) #front
- df.replace('s+$', '', regex=True, inplace=True) #end
- df.values
- df_obj = df.select_dtypes(['object'])
- print (df_obj)
- 0 a
- 1 c
- df[df_obj.columns] = df_obj.apply(lambda x: x.str.strip())
- print (df)
- 0 1
- 0 a 10
- 1 c 5
- df[0] = df[0].str.strip()
- >>> df = pd.DataFrame([[' a ', 10], [' c ', 5]])
- >>> df[0][0]
- ' a '
- >>> df[0] = df[0].apply(lambda x: x.strip())
- >>> df[0][0]
- 'a'
- >>> df = pd.DataFrame([[' a ', 10], [' c ', 5]])
- >>> df.apply(lambda x: x.apply(lambda y: y.strip() if type(y) == type('') else y), axis=0)
- 0 1
- 0 a 10
- 1 c 5
- >>> df.replace('(^s+|s+$)', '', regex=True, inplace=True)
- >>> df
- 0 1
- 0 a 10
- 1 c 5
- >>> df[0] = df[0].str.strip()
- df[0] = df[0].str.strip()
- non_numeric_columns = list(set(df.columns)-set(df._get_numeric_data().columns))
- df[non_numeric_columns] = df[non_numeric_columns].apply(lambda x : str(x).strip())
- df.applymap(lambda x: x.strip() if type(x) is str else x)
- import pandas as pd
- def trimAllColumns(df):
- """
- Trim whitespace from ends of each value across all series in dataframe
- """
- trimStrings = lambda x: x.strip() if type(x) is str else x
- return df.applymap(trimStrings)
- # simple example of trimming whitespace from data elements
- df = pd.DataFrame([[' a ', 10], [' c ', 5]])
- df = trimAllColumns(df)
- print(df)
- >>>
- 0 1
- 0 a 10
- 1 c 5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement