0

I have a pandas dataframe with all floats. I'd like to turn these into integers, with thousands-separator. For example, 10000.00 would be 10,000. The dataframe only has floats with no null value.

Currently I am looping on the dataframe's rows. Example code:

for i in range(df.shape[0]):
    df.iloc[i, :] = df.iloc[i, :].astype(int).apply('{:,}'.format)

Is there a more efficient way to do this? Preferably in one line?

Thanks in advance!

SAKURA
  • 937
  • 11
  • 29
  • 1
    Possible duplicate of [Format a number to commas to separate thousands in Python](https://stackoverflow.com/questions/43102734/format-a-number-to-commas-to-separate-thousands-in-python) – G. Anderson Oct 17 '18 at 14:53
  • Use `df.apply(lambda x: x.apply('{:,.0f}'.format))` – Zero Oct 17 '18 at 14:53

1 Answers1

0

.applymap() can apply a function across each of the elements in a whole dataframe:

In [14]: df
Out[14]:
               0              1              2              3              4
0  178711.734521  118958.200494   54379.699539   72575.737361  129236.395323
1  132075.638310   37217.504969  131311.983325   35175.116276  191367.853498
2  102123.073075    9860.698108   41645.629665    4240.177466    4670.187517
3   57162.513788   34473.448018  197430.723197  101702.904956   31658.275327
4  199243.246008  143353.212629   79133.130402  143414.562742   85171.281362

In [15]: df.applymap('{:,.0f}'.format)
Out[15]:
         0        1        2        3        4
0  178,712  118,958   54,380   72,576  129,236
1  132,076   37,218  131,312   35,175  191,368
2  102,123    9,861   41,646    4,240    4,670
3   57,163   34,473  197,431  101,703   31,658
4  199,243  143,353   79,133  143,415   85,171
Randy
  • 14,349
  • 2
  • 36
  • 42