Hatshepsut
Hatshepsut

Reputation: 6642

Lowercase columns by name using dataframe method

I have a dataframe containing strings and NaNs. I want to str.lower() certain columns by name to_lower = ['b', 'd', 'e']. Ideally I could do it with a method on the whole dataframe, rather than with a method on df[to_lower]. I have

df[to_lower] = df[to_lower].apply(lambda x: x.astype(str).str.lower())

but I would like a way to do it without assigning to the selected columns.

df = pd.DataFrame({'a': ['A', 'a'], 'b': ['B', 'b']})
to_lower = ['a']
df2 = df.copy()
df2[to_lower] = df2[to_lower].apply(lambda x: x.astype(str).str.lower())

Upvotes: 0

Views: 279

Answers (2)

akuiper
akuiper

Reputation: 214927

You can use assign method and unpack the result as keyword argument:

df = pd.DataFrame({'a': ['A', 'a'], 'b': ['B', 'b'], 'c': ['C', 'c']})
to_lower = ['a', 'b']

df.assign(**df[to_lower].apply(lambda x: x.astype(str).str.lower()))

#   a   b   c
#0  a   b   C
#1  a   b   c

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249113

You want this:

for column in to_lower:
    df[column] = df[column].str.lower()

This is far more efficient assuming you have more rows than columns.

Upvotes: 0

Related Questions