我有一个pandas数据框,有些行是数字,我想将它们转换为千位分隔符。尝试过此thousands=','
但不起作用,尝试了其他解决方案,但是如何在to_csv
我想要的例子
将31752000
转换为31,752,000
这是我正在尝试的代码:
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)
答案 0 :(得分:1)
您可以这样手动添加逗号(仅适用于数字小于1,000,000,000的逗号):
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)