IriSandivel
IriSandivel

Reputation: 103

change a fraction of a column in a dataframe based on other information in Pandas

I have this DataFrame

Person      Salary 
John         350
Peter        543
Susan        517
Carl         448

And I have this other dataframe with the changes that I have to make to the first

 Attribute    Change
  Person         3
  Salary         2

The value of "Change" should refer to changing the amount that appears by another letter, for example "x". The result should look like this:

   Person      Salary 
    Jxxx         3xx
    Pexxx        5xx
    Suxxx        5xx
    Cxxx         4xx

How could I do this?

Upvotes: 3

Views: 502

Answers (2)

Dennis Lyubyvy
Dennis Lyubyvy

Reputation: 1120

The data:

import pandas as pd

df = pd.DataFrame({'Person':['John', 'Peter', 'Susan','Carl'],
'Salary':[350,543,517,448]})

change_df = pd.DataFrame({'Attribute':['Person', 'Salary'],
'Change':['3','2']})

The solution:

for col in df.columns:
    k = int(change_df[change_df.Attribute == col].Change)
    df[col] = df[col].apply(lambda x: str(x)[:len(str(x))-k]+k*'x')

The result:

  Person Salary
0   Jxxx    3xx
1  Pexxx    5xx
2  Suxxx    5xx
3   Cxxx    4xx

Upvotes: 1

Alessandro Solbiati
Alessandro Solbiati

Reputation: 979

A concise and elegant answer consists in first in creating a mapping from your mapping_df, and then apply a function following that mapping on your target_df.

You can get a mapping from your mapping_df with transpose

>>> mapping_df.transpose().to_dict()
{1: {'Attribute': 'Person', 'Change': '3'},
 2: {'Attribute': 'Salary', 'Change': '2'}}

And then just apply it to your target_dataframe using map

cleaned = pd.DataFrame()

for mapping in list(mapping_df.transpose().to_dict().values()):
    cleaned[mapping['Attribute']] = target_df[mapping['Attribute']].map(
        lambda s: s[: - int(mapping['Change']) ]+ int(mapping['Change']) *'x')

You will get the intended output

 >>> cleaned
    Person  Salary
1   Jxxx    3xx
2   Pexxx   5xx
3   Suxxx   5xx
4   Cxxx    4xx

Upvotes: 1

Related Questions