Reputation: 5559
I want to make all strings lower case and remove the whitespaces at the beginning and end of the strings.
df = pandas.DataFrame(data=[1,2,3,'A'],columns=['A'])
df['A'] = numpy.where(
df['A'].apply(lambda x: isinstance(x, str)),
df['A'].str.lower().str.strip(),
df['A'],
)
The problem is that the code above fails if none of the rows is a string.
df = pandas.DataFrame(data=[1,2,3],columns=['A'])
AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas
Is there a better way to do this than
for index in df['A'].index:
if isinstance(df['A'].iloc[index], str):
df['A'].iloc[index] = df['A'].iloc[index].str.lower().str.strip()
Upvotes: 0
Views: 1414
Reputation: 4343
Assuming you want to leave your non strings untouched, you can use:
df['A']=df['A'].apply(lambda x: x.lower().strip() if isinstance(x, str) else x)
Upvotes: 4