Reputation: 147
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.
Upvotes: 0
Views: 200
Reputation: 147
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.
Upvotes: 1
Reputation: 22031
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))
Upvotes: 1