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()
df['A']=df['A'].apply(lambda x: x.lower().strip() if isinstance(x, str) else x)