DataFrame max()不返回最大值

时间:2018-07-29 04:25:48

标签: python dataframe ipython gspread

这里是真正的初学者问题,但这很简单,我真的很困惑。 Python / DataFrame新手。

我已经从Google表格中加载了DataFrame,但是任何图形绘制或尝试计算都会产生虚假结果。加载代码:

# Setup
!pip install --upgrade -q gspread

from google.colab import auth
auth.authenticate_user()

import gspread
from oauth2client.client import GoogleCredentials

gc = gspread.authorize(GoogleCredentials.get_application_default())

worksheet = gc.open('Linear Regression - Brain vs. Body Predictor').worksheet("Raw Data")

rows = worksheet.get_all_values()

# Convert to a DataFrame and render.
import pandas as pd
df = pd.DataFrame.from_records(rows)

这似乎工作正常,并且在我打印出DataFrame时似乎可以正确加载数据,但是运行max()显然会返回错误的结果。例如:

print(df[0])
print(df[0].max())

将输出:

0     3.385
1      0.48
2      1.35
3       465
4     36.33
5     27.66
6     14.83
7      1.04
8      4.19
9     0.425
10    0.101
11     0.92
12        1
13    0.005
14     0.06
15      3.5
16        2
17      1.7
18     2547
19    0.023
20    187.1
21      521
22    0.785
23       10
24      3.3
25      0.2
26     1.41
27      529
28      207
29       85
      ...  
32     6654
33      3.5
34      6.8
35       35
36     4.05
37     0.12
38    0.023
39     0.01
40      1.4
41      250
42      2.5
43     55.5
44      100
45    52.16
46    10.55
47     0.55
48       60
49      3.6
50    4.288
51     0.28
52    0.075
53    0.122
54    0.048
55      192
56        3
57      160
58      0.9
59     1.62
60    0.104
61    4.235
Name: 0, Length: 62, dtype: object
Max: 85

显然,最大值已淘汰-应该是6654,而不是85。

我到底在做错什么?

第一篇StackOverflow帖子,在此先感谢。

1 个答案:

答案 0 :(得分:0)

如果您选中它,则会在print()的末尾看到dtype=object。另外,您会注意到您的大熊猫Series具有“ int”值和“ float”值(例如,同一位置有66543.5系列)。

这些很好的提示您有一系列字符串,这里的max运算符基于字符串比较进行比较。但是,您希望有一系列数字(特别是floats)并根据数字比较进行比较。

检查以下可重现的示例:

>>> df = pd.DataFrame({'col': ['0.02', '9', '85']}, dtype=object)
>>> df.col.max()
'9'

您可以检查一下是因为

>>> '9' > '85'
True

您希望将这些值视为浮点型。使用pd.to_numeric

>>> df['col'] = pd.to_numeric(df.col)
>>> df.col.max()
85

有关strint比较的更多信息,请 check this question