import pandas as pd
import io
import numpy as np
import datetime
data = """
date id
2015-10-31 50230
2015-10-31 48646
2015-10-31 48748
2015-10-31 46992
2015-11-01 46491
2015-11-01 45347
2015-11-01 45681
2015-11-01 46430
"""
df = pd.read_csv(io.StringIO(data), delimiter='\s+', index_col=False, parse_dates = ['date'])
df2 = pd.DataFrame(index=df.index)
df2['Check'] = np.where(datetime.datetime.strftime(df['date'],'%B')=='October',0,1)
我有我正在使用的这个示例。什么df2['Check']
正在做的是,如果df['date'] == 'October'
然后我给你0,否则为1基于另一个数据帧值创建列
np.where
正常工作与其他条件,但strftime
不顺心的一系列导致此错误:
Traceback (most recent call last):
File "C:/Users/Leb/Desktop/Python/test2.py", line 22, in <module>
df2['Check'] = np.where(datetime.datetime.strftime(df['date'],'%B')=='October',0,1)
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'Series'
如果我循环需要很长一段时间我的实际数据约为1M。我怎样才能有效地做到这一点?
df2['Check']
应该是这样的:
Check
0 0
1 0
2 0
3 0
4 1
5 1
6 1
7 1
使用'.dt'访问器。使用熊猫0.17。请参阅[文档](http://pandas.pydata.org/pandas-docs/version/0.17.0/whatsnew.html#dt-accessor)。你得到的错误,因为日期时间与单个参数,而不是数组。 – Kartik
非常有用,我会记住这一点。部分蟒蛇我现在有0.16。 – Leb
不应该'df ['date']。dt.month == 9'即使在'0.16.0'也能正常工作吗? – EdChum