Search code examples
pythonpandasdataframemodulo

Generate new Column in Dataframe with Modulo of other Column


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?


Solution

  • This is a very simple and pythonic solution:

    import pandas as pd
    
    data = [10,11,35,45,65]
    
    df = pd.DataFrame(data, columns=['Day1'])
    
    df['Day2'] = df['Day1'].mod(10)
    
    df
    

    Result

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