简体   繁体   English

pandas 到 csv - 保留“$”作为格式

[英]pandas to csv - preserving “$” as formatting

I have a pandas data frame containing amounts with dollar signs.我有一个 pandas 数据框,其中包含带有美元符号的金额。 When I send this to a csv and open it in Excel I can see the amounts with the $'s, but the $'s are clearly not Excel formatting and when I actually click on a cell all I see is the number and no $.当我将它发送到 csv 并在 Excel 中打开它时,我可以看到带有 $ 的金额,但 $ 显然不是 Excel 格式,当我点击单元格时没有看到 $ . The $ signs are then completely lost when I import this file into something like Tableau.当我将此文件导入 Tableau 之类的文件时,$ 符号会完全丢失。

Is there any way to address this easily in Python?有什么方法可以在 Python 中轻松解决这个问题? (Note that only certain columns contain amounts with $ signs) (请注意,只有某些列包含带有 $ 符号的金额)

Any help is appreciate任何帮助表示赞赏

Convert the type of the column to string.将列的类型转换为字符串。

df['columnname'].astype(str)

To demonstrate this, I make a dataframe where the money column is already strings and then export to csv.为了证明这一点,我创建了一个 dataframe,其中货币列已经是字符串,然后导出到 csv。 I use this code:我使用这段代码:

import pandas as pd
df = pd.DataFrame([[1,'$1.30'],[2,'$1.50'],[3,'$1.70']],columns=['id','money'])
df.to_csv('temp.csv')

The csv file looks like this in excel: csv 文件在 excel 中如下所示:

      id       money
0      1       $1.30 
1      2       $1.50 
2      3       $1.70 

The csv file looks like this in notepad: csv 文件在记事本中如下所示:

,id,money
0,1,$1.30 
1,2,$1.50 
2,3,$1.70 

However, in excel, when I click on the cell that reads $1.30 , in the wide box at the top of the screen it reads 1.3 .但是,在 excel 中,当我单击显示$1.30的单元格时,在屏幕顶部的宽框中显示为1.3 This is excel doing its thing, but don't be fooled, the dollar sign is in the file and it's not just excel formatting.这是 excel 做它的事情,但不要被愚弄,美元符号在文件中,它不仅仅是 excel 格式。 If you load it in Tableau and the $ disappears that is because tableau removed the dollar sign and you have to work on settings in tableau;如果您在 Tableau 中加载它并且 $ 消失,那是因为 tableau 删除了美元符号,您必须在 tableau 中进行设置; changing your python code or the csv file wont fix this.更改您的 python 代码或 csv 文件不会解决此问题。

I then loaded this in tableau and it did remove the dollar signs.然后我将它加载到画面中,它确实删除了美元符号。

Simply right click the axis and choose format.只需右键单击轴并选择格式。 Then click numbers and click currency (standard)然后点击数字并点击货币(标准)

Then hooray!然后万岁!

在此处输入图像描述

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM