【问题标题】:Column String Access for date using day使用日期的日期的列字符串访问
【发布时间】:2017-05-06 14:47:14
【问题描述】:

如何访问数据集中 12 个月的所有天数?

数据的结构是:

print(df.head(n=1)) Date_Time IPAddress Visitors OS Browser \ 0 2016-10-18 12:57:45 104.236.233.18 1001 Mac OS Google Chrome Browser_Version Location Referrer PageID 0 39.0.2171.95 NaN creditcommerty.in index.php

为什么vdf在这段代码中索引值6和2:

print(vdf['new_day'][6][2])

给出这个错误?

print(vdf['new_day'][6][2])
Traceback (most recent call last):
File "<ipython-input-196-c01f93f97338>", line 1, in <module>
print(vdf['new_day'][6][2])
KeyError: 6

【问题讨论】:

  • 您需要显示您的数据。目前没有提供足够的信息来提供帮助。
  • 查看数据结构如下: print(df.head(n=1)) Date_Time IPAddress Visitor OS Browser \ 0 2016-10-18 12:57:45 104.236 .233.18 1001 Mac OS Google Chrome Browser_Version Location Referrer PageID 0 39.0.2171.95 NaN creditcommerty.in index.php
  • 查看数据结构如下: print(df.head(n=1)) Date_Time IPAddress Visitor OS Browser \ 0 2016-10-18 12:57:45 104.236 .233.18 1001 Mac OS Google Chrome Browser_Version Location Referrer PageID 0 39.0.2171.95 NaN creditcommerty.in index.php
  • #获取第6行和第2两个值即DAY print(df['new_day'][6][2]) 19 value_list = [12] vdf= pd.DataFrame(df [df.month.isin(value_list)]) print(vdf.head(n=1)) 现在,当我尝试访问我之前所做的数据帧的 DAY 部分时,它会出现以下错误:
  • print(vdf['new_day'][6][2]) Traceback(最近一次调用最后一次):文件“”,第 1 行,在 打印(vdf['new_day'][6][2]) KeyError: 6

标签: python string date pandas


【解决方案1】:

首先,您需要向我们展示数据集或任何适当的参考资料。我不知道您的数据是什么样的,我只能猜测。我只能告诉你

  1. 由于"new_day" 列中没有第 7 个元素,因此引发 KeyError。

  2. 要访问数据框中的每个数据点,只需执行 vdf.iloc[:,:]vdf[:][:]df。打印其中任何三个都将返回相同的结果。

编辑:从您的 cmets 看来,您的 new_day 列似乎包含三个元素的列表,其中第一个是年份、第二个月和第三天。你想像我假设的那样返回所有的日子吗?

vdf['new_day'][:][2] 应该会为您提供所有当天元素的列表。

>>> vdf = pd.DataFrame([
[[1,2,3]],
[[4,5,6]],
[[7,8,9]]
])

>> vdf
           0
0  [1, 2, 3]
1  [4, 5, 6]
2  [7, 8, 9]

>>> vdf[0][:][2]
[7, 8, 9]

同样,KeyError: 6 被抛出,因为vdf['new_day'[6] 不存在。再次查看您的数据。你有第 7 排吗?

【讨论】:

  • print(df.head(n=1)) Date_Time IPAddress Visitor OS Browser \ 0 2016-10-18 12:57:45 104.236.233.18 1001 Mac OS Google Chrome Browser_Version Location Referrer PageID \ 0 39.0.2171.95 NaN puneetmathur.in index.php new_date new_time 年月 new_day 0 2016-10-18 12:57:45 2016 10 [2016, 10, 18]
  • 导入日期时间 df['new_date'] = [d.date() for d in df['Date_Time']] df['new_time'] = [d.time() for d in df ['Date_Time']] df['year'] = pd.DatetimeIndex(df['new_date']).year df['month'] = pd.DatetimeIndex(df['new_date']).month print(df[ '月']) 打印(df['年'])
  • 这有效: print(df.new_day) print(df['new_day'][6][2]) 19 我需要访问 new_day 中的 Day 列
  • New_Day 看起来像这样: print(df.new_day) 0 [2016, 10, 18] 1 [2016, 10, 18] 2 [2016, 10, 18] 3 [2016, 10, 18 ] 4 [2016, 10, 18]
  • 从 Month value_list = [12] vdf= pd.DataFrame(df[df.month.isin(value_list)]) 过滤掉第 12 个月后,我尝试访问日期的日期部分给出错误 print(vdf['new_day'][6][2]) Traceback (最近一次调用最后一次): KeyError: 6
猜你喜欢
  • 1970-01-01
  • 2012-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多