Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

For Example for this data frame

df = pd.DataFrame({'Age':['12',np.nan,'32','21','55'],

        'Height':["5'7","5'8","5'5",np.nan,"5'10"],

                  'Weight':[np.nan,'160','165','155','170'],

                  'Gender':['M','M',np.nan,'F',np.nan],

                  'Salary':[2900,6550000,7840000,6550000,8950000]})

I want output as:

        Age Height  Weight  Gender  Salary

    0   12  5'7     NaN     M       2.9K

    1   NaN 5'8     160     M       6.55M

    2   32  5'5     165     NaN     7.84M

    3   21  NaN     155     F       6.55M

    4   55  5'10    170     NaN     8.95M 

1 Answer

0 votes
by (36.8k points)

You can use the below code for getting the desired output:

df = pd.DataFrame({'Age':['12',np.nan,'32','21','55'],

        'Height':["5'7","5'8","5'5",np.nan,"5'10"],

                  'Weight':[np.nan,'160','165','155','170'],

                  'Gender':['M','M',np.nan,'F',np.nan],

                  'Salary':[29000,650,7840000,6550000,8950000]})

df['s'] = df['Salary'].apply(lambda x: 

                             str(x/1e6).format('{:.2}')+'M' 

                                 if x >= 1e6 

                             else str(x/1e3).format('{:.2}')+'K'

                                 if x > 1e3

                             else str(x).format('{:,}'))

Output:

   Age Height Weight Gender   Salary      s

0   12    5'7    NaN      M    29000  29.0K

1  NaN    5'8    160      M      650    650

2   32    5'5    165    NaN  7840000  7.84M

3   21    NaN    155      F  6550000  6.55M

4   55   5'10    170    NaN  8950000  8.95M

If you want to know more about the Data Science then do check out the following Data Science which will help you in understanding Data Science from scratch 

Browse Categories

...