0

I have a Pandas dataframe like below.

    X        Y
0  12345    67890
1  54321    N/A
2  67890    123456

I need to make these numbers comma formatted. For example, 12345 => 12,345.

Please help.

Thanks.

Sajan
  • 1,247
  • 1
  • 5
  • 13
Joydeep
  • 147
  • 14
  • See this [thread](https://stackoverflow.com/questions/20686629/how-to-convert-an-integer-to-a-comma-separated-string) – agastya May 09 '20 at 12:37
  • I need all the numbers in the whole dataframe to be formatted like that, not one value. Also, note that, there is a string value there. It should not be changed. – Joydeep May 09 '20 at 13:16
  • Use the apply function on the column. Filter out the ints using lambda – agastya May 09 '20 at 13:28

2 Answers2

1
nan = 'N/A'

df = pd.DataFrame({'A':np.random.randint(10000,20000, 6), 'B':np.random.randint(1000,2000, 6)})
df.loc[3,'B'] = nan

df = df.replace(nan, 0)
df['A'] = df['A'].apply(lambda x: '{:,}'.format(x))
df['B'] = df['B'].apply(lambda x: '{:,}'.format(x))
Marco Cerliani
  • 21,233
  • 3
  • 49
  • 54
1
df['Y'] = df['Y'].apply(pd.to_numeric, errors='coerce')
df['Y'] = df['Y'].apply(lambda x: '{:,.0f}'.format(x))
df['Y'] = df['Y'].replace({'nan' : 'N/A'}, regex=True)

I guess there must be better ways. Thanks Marco Cerliani.

Joydeep
  • 147
  • 14