Home > Enterprise >  Lambda function with loop and condition
Lambda function with loop and condition

Time:06-16

I have a column in Pandas DataFrame which I would like to process for all rows.

Example:

df_column:
    0     urewjf, abc, urewurwe
    1     fdsfs, kjf, oirpiewpoirew...
    2     ab, yryrewy, popof...

What I want to do with thouse values:

  • add blank space in the beginning of the strings which have len<4 EXAMPLE: ' abc', ' ab'

I was trying to convert each row/Series into string and then run lambda function to apply it for each row:

list(map(lambda x: (x.rjust(5) for x in df.column if len(x) < 4), df.column))

It was not working.

Also, I have issues when I use .apply() because of the Series type, but apparantly my lambda function is not constructed correctly.

Any ideas? Thank you in advance

CodePudding user response:

You can just use a pandas vectorised string methods:

df.<your_column_name> = df.<your_column_name>.str.rjust(5)

CodePudding user response:

df = pd.DataFrame({
    "TX_F1": [
        "urewjf",
        "fdsfs",
    ],
    "TX_F2": [
        "abc",
        "kjf"
    ]
})

df.applymap(lambda x: str(x).rjust(5))
  • Related