How do I convert a number to thousand separator using comma?
本问题已经有最佳答案,请猛点这里访问。
我有一个熊猫数据框,一些行是数字,我想把它们转换成千位分隔符。尝试过这个
我想要的例子:将
这是我正在尝试的代码:
1 2 3 4 5 6 7 8 | url = 'https://finance.yahoo.com/quote/RDS-A/balance-sheet?p=RDS-A' table = pandas.read_html(url, attrs={ 'class': 'Lh(1.7) W(100%) M(0)'}, header=0) df = pandas.DataFrame(table[0]) print(df) #Then save to csv #df.to_csv('ydata.csv', index=False, header=True) |
您可以这样手动添加逗号(仅适用于小于100000000的数字):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | thousandSeperatedStrings=[] for x in df: string="" if(x>=1000000): x=x%1000000000 string=str(int(x/1000000))+"," x=x%1000000 string=string+str(int(x/100000)) x=x%100000 string=string+str(int(x/10000)) x=x%10000 string=string+str(int(x/1000))+"," x=x%1000 string=string+str(int(x/100)) x=x%100 string=string+str(int(x/10)) x=x%10 string=string+str(int(x)) elif(x>=1000): x=x%1000000 string=string+str(int(x/1000))+"," x=x%1000 string=string+str(int(x/100)) x=x%100 string=string+str(int(x/10)) x=x%10 string=string+str(int(x)) else: string=str(int(x)) thousandSeperatedStrings.append(string) |