简体   繁体   中英

Python rounding columns to two floating points

I have the question: Round the profit and sales columns to two floating points. Superstore is a dataset I have imported as a pandas dataframe. The code I have written is:

superstore = superstore[superstore['Sales'] != ' 16GB']

#part 4
superstore['Profit'] = superstore['Profit'].round(2)
superstore['Sales'].apply(lambda x: float(x))
#sales = float(superstore['Sales'])
numeric_filter = filter(str.isdigit, superstore['Sales'])
#sales = float(raw_input('Sales'))

superstore['Sales'] = superstore['Sales'].round(2)

I keep getting the error, "TypeError: can't multiply sequence by non-int of type 'float'" and I am unsure of how to fix this. The error is on the line, "superstore['Sales'] = superstore['Sales'].round(2)".

Try:

superstore['Sales'].astype(float).round(2)

Perhaps your column has some values that could not be cast to float:

df=pd.DataFrame({'Sales':[2.53,78.3,54,'ali']})
df['Sales'].round(2)

Which produces:

TypeError: can't multiply sequence by non-int of type 'float'

In order to find non-float values, try:

for i in df['Sales']:
    print(float(i))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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