gpt4 book ai didi

python - DataFrame max()不返回最大值

转载 作者:行者123 更新时间:2023-12-05 05:15:22 25 4
gpt4 key购买 nike

这里是真正的初学者问题,但它如此简单,我真的很难过。 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 帖子,在此先感谢您。

最佳答案

如果检查它,您会在 print() 的末尾看到 dtype=object。此外,您会注意到您的 pandas Series 具有“int”值和“float”值(例如,您有 66543.5 在同一系列中)。

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

检查以下可重现的示例:

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

你可以检查一下,因为

>>> '9' > '85'
True

您希望将这些值视为 float 。使用 pd.to_numeric

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

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

关于python - DataFrame max()不返回最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51577205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com