Pandas Dataframe Numbers Comma Formatted

Python python at python.invalid
Sat May 9 11:38:34 EDT 2020


Joydeep C wrote:
> On Sat, 09 May 2020 17:24:41 +0200, Python wrote:
> 
>> Joydeep C wrote:
>>> On Sat, 09 May 2020 15:46:27 +0200, Python wrote:
>>>
>>>> Joydeep C wrote:
>>>>> On Sat, 09 May 2020 14:42:43 +0200, Python wrote:
>>>>>
>>>>>> Joydeep wrote:
>>>>>>> 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.
>>>>>>
>>>>>>     >>> value = 12345 f'{value:,}'  # >= 3.6
>>>>>> '12,345'
>>>>>>     >>> '{:,}'.format(value)  # >= 2.7
>>>>>> '12,345'
>>>>>
>>>>> I need all the numbers in the whole dataframe to be formatted like
>>>>> that,
>>>>> not one value.
>>>>
>>>>    >>> data.applymap((lambda x: f"{x:,}") )
>>>>            X         Y
>>>> 0  12,345  67,890.0 1  54,321       nan 2  67,890  12,345.0
>>>>    >>> data.apply(np.vectorize((lambda x: f"{x:,}")))
>>>>            X         Y
>>>> 0  12,345  67,890.0 1  54,321       nan 2  67,890  12,345.0
>>>
>>> It's giving error - "Cannot specify ',' with 's'."
>>
>> It means that you're not storing numbers in your dataframe but strings,
>> which is likely not what you want here. Fix that first.
> 
> Of course, they are strings. It's "N/A", not nan.

So convert back to float in the lambda, when appropriate, then use the
format string.





More information about the Python-list mailing list