[英]Convert a column from a pandas DataFrame to float with nan values
[英]Output of column in Pandas dataframe from float to currency (negative values)
我有以下數據框(由負數和正數組成):
df.head()
Out[39]:
Prices
0 -445.0
1 -2058.0
2 -954.0
3 -520.0
4 -730.0
我正在嘗試將“價格”列更改為在將其導出到Excel電子表格時顯示為貨幣。 我使用的以下命令效果很好:
df['Prices'] = df['Prices'].map("${:,.0f}".format)
df.head()
Out[42]:
Prices
0 $-445
1 $-2,058
2 $-954
3 $-520
4 $-730
現在我的問題是,如果我希望輸出在美元符號之前有負號,我該怎么辦? 在上面的輸出中,美元符號在負號之前。 我正在尋找這樣的東西:
請注意,也有正數。
您可以使用np.where
並測試值是否為負數,如果是,則在美元前面添加一個負號,並使用astype
將該系列轉換為字符串:
In [153]:
df['Prices'] = np.where( df['Prices'] < 0, '-$' + df['Prices'].astype(str).str[1:], '$' + df['Prices'].astype(str))
df['Prices']
Out[153]:
0 -$445.0
1 -$2058.0
2 -$954.0
3 -$520.0
4 -$730.0
Name: Prices, dtype: object
您可以使用locale
模塊和_override_localeconv
dict。 它沒有很好的記錄,但這是我在另一個回答中發現的一個技巧,它曾幫助過我。
import pandas as pd
import locale
locale.setlocale( locale.LC_ALL, 'English_United States.1252')
# Made an assumption with that locale. Adjust as appropriate.
locale._override_localeconv = {'n_sign_posn':1}
# Load dataframe into df
df['Prices'] = df['Prices'].map(locale.currency)
這將創建一個如下所示的數據框:
Prices
0 -$445.00
1 -$2058.00
2 -$954.00
3 -$520.00
4 -$730.00
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.