Create new Column in Dataframe with Modulo of other Column

Question:

I would like to create a new column "Day2" which takes the second digit of column named "Days", so if we have Days equal to 35, we would take the number 5 to be in "Day2", I tried this but it’s not working:

DF["Day2"] = DF["Days"].where(
            DF["Days"] < 10,
            (DF["Days"] / 10 % 10).astype(int),
        )

It seems it’s taking the first digit but never the second one, can someone help?

Asked By: the phoenix

||

Answers:

I tried this myself and came up with a very simple solution:

import pandas as pd

data = [10,11,35,45,65]

df = pd.DataFrame(data, columns=['Day1'])

df['Day2'] = df['Day1'] % 10

df

Result

       Day1 Day2
   0    10  0
   1    11  1
   2    35  5
   3    45  5
   4    65  5

Following your approach you can also do:

df['Day2'] = [df["Day1"].where(
        df["Day1"] < 10,
        (df["Day1"] % 10).astype(int),
    )

You need to remove the / 10. It always gives you the decimal numbers which divided by % 10 always gives back the very same decimal number since it is always smaller than 10.

Update:

df['Day2'] = df["Day1"].mod(10)

Yields the same and more pythonic result.

Answered By: Bending Rodriguez
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.