gpt4 book ai didi

python - 尝试访问 Pandas 系列中的元素时出错

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

我正在尝试做一些非常简单的事情:

last_id = len(bg_dt['time']) - 1
last_time = insight_date_to
if last_id > 0:
print("last_id is %d"%last_id)
print(bg_dt['time'])
print(type(bg_dt['time']))
print(type(last_id))
print(bg_dt['time'][0])
last_time = bg_dt['time'][last_id]

这会产生以下输出:

Name: time, dtype: datetime64[ns]
<class 'pandas.core.series.Series'>
<class 'int'>

KeyError: 0

这是怎么回事?这是我已验证的内容:

  • 我正在使用 int 作为索引
  • 我正在尝试将 [] 用于系列
  • 我不会越界

就细节而言,我正在使用 Python 3 并在 Jupyter 笔记本上运行它。

下面是 bg['time'] 的例子:

442751   2016-04-26 09:00:00
445544 2016-04-26 18:00:00
445539 2016-04-27 09:00:00
450923 2016-04-27 18:00:00
450922 2016-04-28 09:00:00
474301 2016-04-29 18:00:00
474298 2016-04-30 09:00:00
474300 2016-04-30 09:00:00
474299 2016-04-30 18:00:00

这里是 insight_date_to,一个日期时间对象,2016-05-01 00:00:00

最佳答案

我认为更好的方法是使用 iloc , 正如指出的那样 conner.xyz0 选择第一个值,用 -1 选择最后一个值:

print bg_dt
time
442751 2016-04-26 09:00:00
445544 2016-04-26 18:00:00
445539 2016-04-27 09:00:00
450923 2016-04-27 18:00:00
450922 2016-04-28 09:00:00
474301 2016-04-29 18:00:00
474298 2016-04-30 09:00:00
474300 2016-04-30 09:00:00
474299 2016-04-30 18:00:00

print(bg_dt.iloc[0].time)
print(bg_dt.iloc[-1,:].time)
2016-04-26 09:00:00
2016-04-30 18:00:00

或者:

print(bg_dt.time.iloc[0])
print(bg_dt.time.iloc[-1])
2016-04-26 09:00:00
2016-04-30 18:00:00

检查 DataFrameempty :

bg_dt = pd.DataFrame()

if not bg_dt.empty:

print(bg_dt.iloc[0].time)
print(bg_dt.iloc[-1,:].time)

print(bg_dt.time.iloc[0])
print(bg_dt.time.iloc[-1])

关于python - 尝试访问 Pandas 系列中的元素时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37146810/

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