真正的初学者问题,但它是如此简单,我真的很困惑。Python/DataFrame新手。
我已经从谷歌的工作表中加载了一个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帖子,所以提前谢谢。
发布于 2018-07-29 04:33:09
如果您检查它,您将在print()的末尾看到那个dtype=object。此外,你会注意到你的熊猫Series有"int“值和"float”值(例如,在同一系列中有6654和3.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有关str和int比较的更多信息,请参见https://stackoverflow.com/questions/3270680/how-does-python-2-compare-string-and-int-why-do-lists-compare-as-greater-than-n
https://stackoverflow.com/questions/51577205
复制相似问题