【发布时间】:2017-05-07 05:25:01
【问题描述】:
读取数据集:
visits= pd.read_csv('tracker.csv', low_memory=False, parse_dates=
['Date_Time'])
df= pd.DataFrame(visits)
这是数据的外观:
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 http://www.puneetmathur.in/ index.php
问题在于 Date_Time 列:
import datetime
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
目的是根据月份获得从 1 到 30 或 31 或 28 的所有天数 = 12。
下面转换为String并拆分值以访问拆分后的DAY值:
strdt=str(df.new_date)
df['new_date']=df['new_date'].astype(str)
df['new_date']=df.new_date.apply(str)
type(df.new_date)
df['new_day']=df.new_date.str.split('-')
Pandas Dataframe 有超过 1000 行,所以这不是问题:
print(df.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]
5 [2016, 10, 18]
6 [2016, 10, 19]
7 [2016, 10, 19]
8 [2016, 10, 19]
9 [2016, 10, 19]
10 [2016, 10, 19]
11 [2016, 10, 19]
12 [2016, 10, 19]
13 [2016, 10, 19]
14 [2016, 10, 19]
15 [2016, 10, 19]
16 [2016, 10, 19]
17 [2016, 10, 19]
18 [2016, 10, 20]
19 [2016, 10, 20]
20 [2016, 10, 20]
我想访问第二个逗号两位数之后的第三个值 打印(df['new_day'][6][2]) 19
到目前为止一切顺利..
我现在先用月份过滤日期,然后尝试使用以下代码访问第二个逗号后的值:2 位数的值:
value_list = [12]
vdf= pd.DataFrame(df[df.month.isin(value_list)])
print(vdf[:][:].head(n=1))
print(vdf[:][:].head(n=1))
Date_Time IPAddress Visitors OS Browser \
2836 2016-12-11 01:25:25 66.102.8.217 3955 Search Bot Apple Safari
Browser_Version Location Referrer \
2836 9 Florida, United States http://www.puneetmathur.in/
PageID new_date new_time year month new_day
2836 index.php 2016-12-11 01:25:25 2016 12 [2016, 12, 11]
当我尝试访问第二个值时,它会给出奇怪的输出:
vdf['new_day'][:][:2].str.split('-')
Out[250]: Series([], Name: new_day, dtype: object)
以下内容也无法在第二个逗号之后给我 new_day 的第三列中的所有值。 请告诉我如何访问 new_day 的第 3 列中的 DAY 值
vdf.iloc[:,:]
【问题讨论】:
-
这太长了!这里的基本建议:只需将一列存储为 pandas 日期时间。使用 dt 访问器访问值(请参阅此处的文档:pandas.pydata.org/pandas-docs/stable/basics.html#dt-accessor)对于 pandas,将列表存储在列中通常是个坏主意。如果您有一个长度为 3 的列表的单列,您会发现最好将其存储为 3 个单独的列,每列中有一个值(或者在这里更好,只需存储为 dtype datetime 的单列然后使用 dt 访问器)
-
不知道为什么你在
read_csv中传递parse_dates,然后你通过尝试转换回字符串来扭转所有的好工作。基本上,一旦你完成了解析,你就可以使用.dt访问日期时间属性,因此日将是df['Date_Time'].dt.day,月是...dt.month,同样是年。如果您只想要日期,那么您也可以使用dt.date,但这会为您提供一个datetime.date对象,它比字符串有用但更有用 -
嘿 @EdChum 你的建议 df['Date_Time'].dt.day 工作得非常好,下面的工作也很好:df['Date_Time'].dt.day df['Date_Time']。 dt.month df['Date_Time'].dt.year df['Date_Time'].dt.date df['Date_Time'].dt.time df['Date_Time'].dt.hour df['Date_Time']。 dt.minute df['Date_Time'].dt.second 再次感谢 EdChum 我接受这个作为答案
-
关于如何选择 Month==12 的任何想法 @EdChum 以下代码给出错误:df['Date_Time'].dt.month=='12' TypeError: invalid type comparison
标签: python string date pandas dataframe