SoFunction
Updated on 2024-10-29

The pandas implementation of modifying DataFrame column names

put

There exists a DataFrame named dataset

>>> 
Index(['age', 'job', 'marital', 'education', 'default', 'housing', 'loan',
    'contact', 'month', 'day_of_week', 'duration', 'campaign', 'pdays',
    'previous', 'poutcome', '', '',
    '', 'euribor3m', '', 'y'],
   dtype='object')

Now, I'm going to change the name of its columns to.

>>> new_columns
Index(['age_0', 'job_1', 'marital_2', 'education_3', 'default_4', 'housing_5',
    'loan_6', 'contact_7', 'month_8', 'day_of_week_9', 'duration_10',
    'campaign_11', 'pdays_12', 'previous_13', 'poutcome_14',
    '.rate_15', '.idx_16', '.idx_17',
    'euribor3m_18', 'nr.employed_19', 'y_20'],
   dtype='object')

How does it work?

settle (a dispute)

I. Modified by the class's own attributes.

1. Brainless assignment of direct modification

>>> # Solve the `new_columns` derivation problem first
>>> # List derivation
>>> new_columns_list = [column_str+'_'+str(i) for i ,column_str in enumerate()]
>>> # Type conversion
>>> new_columns = (new_columns_list)
>>>  = new_columns

2. through the .map(mapper, na_action=None) function to modify the

>>> # Note: mapper makes use of lambda expressions.
>>> # But I can't seem to find a way to change two values in a lambda expression
>>> # So it's just a lame use of a global variable, i, and a mapping function, mapper().
>>> # I hope you can help me find a way

>>> i = 0
>>> def mapper(x): # The mapping function, mapper
  global i
  x += '_' + str(i)
  i += 1
  return x
>>> (mapper)

3. Reference blogs use objects

Having rummaged through the documentation with help(), the

I haven't been able to find a way to use it, so I thought I'd take the time to translate the document.

II. Modification through the () function

1. Violent dictionary method (benefit: you can only modify specific columns)

>>> # Dictionary derivation is used here first #
>>> new_dict = {
  key:key+'_'+str(i)
  for i, key in enumerate()
  }
>>> (columns=new_dict, inplace=True)

2. Mapping modification method

>>> # The original blog post still uses lambda expressions
>>> # I'll just copy it again, copy it from above #
>>> # crappy use of a global variable i, and the mapping function mapper()

>>> i = 0
>>> def mapper(x): # The mapping function, mapper
  global i
  x += '_' + str(i)
  i += 1
  return x
(columns=mapper, inplace=True)

To summarize: Dictionary derivation and list derivation are used in a similar way, the main difference being the choice between parentheses and curly braces.

This is the whole content of this article.