例如此数据框

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]})


我希望输出为:

        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

最佳答案

一种选择:

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('{:,}'))




   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

关于python - 如何在pandas DataFrame中将值转换为6200000到6.2M或1900到1.90K的列?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56942480/

10-12 14:25