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