safex
safex

Reputation: 2514

panda assign column names in method chain

I can assign a list as column names in pandas easily in one line, but (how) can I do the same thing in a method chain?

import pandas as pd
df = pd.DataFrame(data={'a':[1,2], 'b':[2,4]})

new_column_names =['aa', 'bb']

# classical way:
df.columns= new_column_names

What I want is to have this a longer method chain:

# method chain
(df.some_chain_method(...)
   .another_chain_method(...)
   .assign_columnnames(new_columns_names))

You can assume you know the number of columns and it matches new_column_names

Upvotes: 5

Views: 1173

Answers (2)

Rockgecko
Rockgecko

Reputation: 36

I think you can also use the .rename() method, with the inplace option enabled, for example:

import pandas as pd
df = pd.DataFrame(data={'a':[1,2], 'b':[2,4]})
df.rename(columns={"a": "aa", "b":"bb"}, inplace=True)
df

which results in

    aa  bb
0   1   2
1   2   4

Using rename means you can change just a subset of the column names.

See https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename.html

Upvotes: 0

Scott Boston
Scott Boston

Reputation: 153460

Yes, use set_axis:

df.set_axis(new_column_names, axis=1)

Output:

   aa  bb
0   1   2
1   2   4

Note, in older version of pandas set_axis defaulted with inplace=True, so you'll need to add inplace=False to chain other methods. Recently, it was changed to inplace=False default.

Example with chaining:

df.set_axis(new_column_names, axis=1).eval('cc = aa + bb')

Output:

   aa  bb  cc
0   1   2   3
1   2   4   6

Upvotes: 8

Related Questions