Ich habe ein Datenfeld, das eine Spalte namens "Lead Rev" hat. Diese Spalte ist ein Feld mit Zahlen wie (100000 oder 5000 usw.). Ich möchte wissen, wie man diese Zahlen formatiert, um Kommas als tausend Trennzeichen anzuzeigen.
Ist es etwa so: '{:,}'. Format ('Lead Rev')
"Lead Rev" ist mein Spaltenname. Ich habe über 200.000 Zeilen in meinem Datensatz.
ValueError Traceback (letzter Aufruf zuletzt) in () ----> 1 '{:,}'. format ('Lead Rev')
ValueError: ',' oder '_' kann nicht mit 's' angegeben werden.
Sie können apply () verwenden, um das gewünschte Ergebnis zu erhalten. Das funktioniert auch beim Floating
import pandas as pd
series1 = pd.Series({'Value': 353254})
series2 = pd.Series({'Value': 54464.43})
series3 = pd.Series({'Value': 6381763761})
df = pd.DataFrame([series1, series2, series3])
print(df.head())
Value
0 3.532540e+05
1 5.446443e+04
2 6.381764e+09
df['Value'] = df.apply(lambda x: "{:,}".format(x['Value']), axis=1)
print(df.head())
Value
0 353,254.0
1 54,464.43
2 6,381,763,761.0
Damit alle Floats standardmäßig Kommaseparatoren anzeigen, legen Sie Folgendes fest:
pd.options.display.float_format = '{:,}'.format
https://pandas.pydata.org/pandas-docs/version/0.23.4/options.html
class commaConverter:
"""
add and remove commas to numberstring 1000.00+> 1,000.00
"""
def __init__(self,price):
self.price=price
def addCommas(self):
price=self.price
price=str(price)
try:
priceSplit = price.split('.')
price1 = priceSplit[0]
price2 = priceSplit[1]
except IndexError:
price1 = price
price2 = '00'
price1 = price1.strip(" ")
newPrice = ''
i = 0
for x in price1[::-1]:
if i == 3 and x != '-':
newPrice = x + ',' + newPrice
i = 1
else:
newPrice = x + newPrice
i += 1
commaPrice = newPrice + '.' + priceSplit[1]
return str(commaPrice)
def removeCommas(self):
price=self.price
price=price.replace(',','')
price = price.replace('$', '')
return price
Gruppierungsoptionen wie ,
werden nur für numerische Präsentationstypen unterstützt. Sie müssen einen numerischen Präsentationstyp angeben. Informieren Sie sich über Ihre Optionen .
Sie können die Apply- oder Stack-Methode verwenden
df.apply(lambda x: x.str.replace(',','.'))
df.stack().str.replace(',','.').unstack()