Python: float() argument must be a string or a number,not 'pandas

醉酒当歌 提交于 2019-12-24 08:06:20

问题


Have the following piece of code through which I am trying to plot a graph:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import mpld3



my_list = [1,2,3,4,5,7,8,9,11,23,56,78,3,3,5,7,9,12]

new_list = pd.Series(my_list)

df1 = pd.DataFrame({'Range1':new_list.value_counts().index, 'Range2':new_list.value_counts().values})

df1.sort_values(by=["Range1"],inplace=True)

df2 = df1.groupby(pd.cut(df1["Range1"], [0,1,2,3,4,5,6,7,8,9,10,11,df1['Range1'].max()])).sum()

objects = df2['Range2'].index

y_pos = np.arange(len(df2['Range2'].index))

plt.bar(df2['Range2'].index.values, df2['Range2'].values)

but getting the following error message:

TypeError: float() argument must be a string or a number, not 'pandas._libs.interval.Interval'

Not getting from where this float error is coming. Any suggestion is highly appreciated.


回答1:


Matplotlib cannot plot category datatypes. You would need to convert to a string.

plt.bar(df2['Range2'].index.astype(str), df2['Range2'].values)




回答2:


The pd.cut operation yields intervals:

In [11]: pd.cut(df1["Range1"], [0,1,2,3,4,5,6,7,8,9,10,11,df1['Range1'].max()])
Out[11]:
12      (0, 1]
11      (1, 2]
0       (2, 3]
10      (3, 4]
3       (4, 5]
2       (6, 7]
9       (7, 8]
1       (8, 9]
8     (10, 11]
7     (11, 78]
5     (11, 78]
4     (11, 78]
6     (11, 78]
Name: Range1, dtype: category
Categories (12, interval[int64]): [(0, 1] < (1, 2] < (2, 3] < (3, 4] ... (8, 9] < (9, 10] < (10, 11] <
                                   (11, 78]]

When used in the groupby operation, they are matched based on the index of the cut operation above, and then grouped and summed according to the operation you specified.

As a result, the intervals end up as the index in df2:

In [14]: df2
Out[14]:
          Range1  Range2
Range1
(0, 1]         1       1
(1, 2]         2       1
(2, 3]         3       3
(3, 4]         4       1
(4, 5]         5       2
(5, 6]         0       0
(6, 7]         7       2
(7, 8]         8       1
(8, 9]         9       2
(9, 10]        0       0
(10, 11]      11       1
(11, 78]     169       4

When you use df2['Range2'].index.values it will be an array of these intervals passed as the first argument to bar, which is not convertible to a float in the way matplotlib expects.

If you are looking to just plot a bar chart of df2.Range2 and you are happy to have the intervals as the axis labels, this will work:

plt.bar(range(len(df2)), df2.Range2.values, tick_label=df2.Range2.index.values)

and produces this image for me:



来源:https://stackoverflow.com/questions/53619746/python-float-argument-must-be-a-string-or-a-number-not-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!