Colin Zhong
Colin Zhong

Reputation: 747

Python variable to float list

I am using pandas to plot values on each bar. dayspeed['Download'] will generate a Series like this:

0      3.83
1      3.19
2      3.83
3      3.82
4      3.84
5      3.82
6      3.87
7      3.86
8      3.85
9     20.33
10    19.15
11    14.57
12    13.06
13     3.82
14     3.11
15     3.83
Name: Download, dtype: float64

but when I apply it to a for loop, it shows integer type values.

labels = ["%d" % i for i in dayspeed['Download']]

labels

['3', '3', '3', '3', '3', '3', '3', '3', '3', '20', '19', '14', '13', '3', '3', '3']

Upvotes: 0

Views: 72

Answers (2)

Chris Montanaro
Chris Montanaro

Reputation: 18202

You need to supply the float flag %f instead of %d (digit/int):

labels = ["%f" % i for i in dayspeed['Download']]

to set float precision to 2:

labels = ["%.2f" % i for i in dayspeed['Download']]

example:

>>> l
[3.19, 2, 3.83, 3, 3.82, 4, 3.84]
>>> ["%f" % i for i in l]
['3.190000', '2.000000', '3.830000', '3.000000', '3.820000', '4.000000', '3.840000']
>>> ["%.2f" % i for i in l]
['3.19', '2.00', '3.83', '3.00', '3.82', '4.00', '3.84']
>>> ["%.4f" % i for i in l]
['3.1900', '2.0000', '3.8300', '3.0000', '3.8200', '4.0000', '3.8400']

Upvotes: 1

maxymoo
maxymoo

Reputation: 36545

You probably want to use vectorised operations on your dataframe since in general this will faster and more concise than a loop or list comprehension:

  • Since your column has the datatype you can np.float64 round by accessing the round method on your dataframe
  • You can convert the datatype of a pandas series with the astype method.
  • You can access the underlying list of values with values.tolist():

For your case something like this: df[c].round(2).astype(str).values.tolist()

Upvotes: 0

Related Questions