虽然可以在控制台中打印小数位数,但是在尝试使用格式正确的数字写入csv时,我面临的挑战要大得多。在下面的代码中,我以某种方式设法将整数除以'000s,并将结果抛出到csv中,但是我无法摆脱多余的“。,”。 for循环确实是一个艰巨的挑战。也许有人可以告诉我如何解决这个难题。
在下面查看代码字符串。应该看起来像,无论是在控制台打印还是在我要写入的csv文件中:
23,400,344.567,54,363,744.678,56,789,117.456,4,132,454.987
输入:
import pandas as pd
def insert_comma(s):
str=''
count=0
for n in reversed(s):
str += n
count+=1
if count == 3:
str += ','
count=0
return ''.join([i for i in reversed(str)][1:])
d = {'Quarters' : ['Quarter1','Quarter2','Quarter3','Quarter4'],
'Revenue':[23400344.567, 54363744.678, 56789117.456, 4132454.987]}
df=pd.DataFrame(d)
df['Revenue']=df.apply(lambda x: insert_comma(str(x['Revenue'] / 1000)), axis=1)
# pd.options.display.float_format = '{:.0f}'.format
df.to_csv("C:\\Users\\jcst\\Desktop\\Private\\Python data\\new8.csv", sep=";")
# round to two decimal places in python pandas
# .options.display.float_format = '{:.0f}'.format
print(df)
输出
Quarters Revenue
0 Quarter1 234,00.,344
1 Quarter2 543,63.,744
2 Quarter3 567,89.,117
3 Quarter4 1,32.,454
答案 0 :(得分:3)
您可以使用它。使用格式字符串对“收入”列中的所有行使用逗号和小数点后3位。
df['Revenue']=df['Revenue'].apply('{0:,.3f}'.format)
结果:
Quarters Revenue
0 Quarter1 23,400,344.567
1 Quarter2 54,363,744.678
2 Quarter3 56,789,117.456
3 Quarter4 4,132,454.987
答案 1 :(得分:1)
建议:
getPalette = colorRampPalette(brewer.pal(9, "Set1") #create a palette with more than 9 colors
chem_colors <-
tibble(Chemical = factor(unique(df$Chemical))) %>%
mutate(color = getPalette(30))
chem_colors <- setNames(chem_colors$color, as.character(chem_colors$Chemical) #create named vector
plot_trials <- function(year) {
ggplot(filter(df, Year == year), aes(x = Trial, y = Concentration, width=0.8)) +
geom_bar(stat = "identity", aes(fill = Chemical)) +
scale_fill_manual(values = chem_colors)
}
像这样工作:
insertCommas = lambda x: format(x, ',')
答案 2 :(得分:0)
这对我有用:
df['Revenue'] = df['Revenue'].apply(lambda x:f"{x:,.3f}")
此解决方案使用Python 3.6+ f-strings插入逗号作为千位分隔符并显示3个小数。