Pandas 数据框中列的输出从浮点数到货币(负值)
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
我试图将 'Prices' 列更改为在将其导出到 Excel 电子表格时显示为货币。我使用的以下命令运行良好:
df['Prices'] = df['Prices'].map("${:,.0f}".format)
df.head()
Out[42]:
Prices
0 $-445
1 $-2,058
2 $-954
3 $-520
4 $-730
现在我的问题是,如果我希望输出在美元符号之前有负号,我该怎么办。在上面的输出中,美元符号在负号之前。我正在寻找这样的东西:
- -445 美元
- -2,058 美元
- -$954
- -520 美元
- -730 美元
请注意也有正数。
您可以使用 np.where
并测试值是否为负数,如果是,则在美元前面添加一个负号,然后使用 astype
:[=13= 将该系列转换为字符串]
In [153]:
df['Prices'] = np.where( df['Prices'] < 0, '-$' + df['Prices'].astype(str).str[1:], '$' + df['Prices'].astype(str))
df['Prices']
Out[153]:
0 -5.0
1 -58.0
2 -4.0
3 -0.0
4 -0.0
Name: Prices, dtype: object
你可以用之前帮助过我的locale
module and the _override_localeconv
dict. It's not well documented, but it's a trick I found in another answer。
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 -5.00
1 -58.00
2 -4.00
3 -0.00
4 -0.00
我有以下数据框(由负数和正数组成):
df.head()
Out[39]:
Prices
0 -445.0
1 -2058.0
2 -954.0
3 -520.0
4 -730.0
我试图将 'Prices' 列更改为在将其导出到 Excel 电子表格时显示为货币。我使用的以下命令运行良好:
df['Prices'] = df['Prices'].map("${:,.0f}".format)
df.head()
Out[42]:
Prices
0 $-445
1 $-2,058
2 $-954
3 $-520
4 $-730
现在我的问题是,如果我希望输出在美元符号之前有负号,我该怎么办。在上面的输出中,美元符号在负号之前。我正在寻找这样的东西:
- -445 美元
- -2,058 美元
- -$954
- -520 美元
- -730 美元
请注意也有正数。
您可以使用 np.where
并测试值是否为负数,如果是,则在美元前面添加一个负号,然后使用 astype
:[=13= 将该系列转换为字符串]
In [153]:
df['Prices'] = np.where( df['Prices'] < 0, '-$' + df['Prices'].astype(str).str[1:], '$' + df['Prices'].astype(str))
df['Prices']
Out[153]:
0 -5.0
1 -58.0
2 -4.0
3 -0.0
4 -0.0
Name: Prices, dtype: object
你可以用之前帮助过我的locale
module and the _override_localeconv
dict. It's not well documented, but it's a trick I found in another answer。
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 -5.00
1 -58.00
2 -4.00
3 -0.00
4 -0.00