[英]Create a column based on another dataframe values
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
在其他條件下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
這是一個稍微簡單的版本,使用datetime
對象的month
屬性。 如果等於10,則將true / false值映射到所需的0/1對:
df2['Check']=df.date.apply(lambda x: x.month==10).map({True:0,False:1})
@ako的答案是金錢,但基於@Kartik和@EdChum的評論,這是我想出的:
import pandas as pd
import io
import numpy as np
data = """
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*125000), delimiter='\s+', index_col=False, names=['date','id'], parse_dates = ['date'])
df2 = pd.DataFrame(index=df.index)
df.shape
(1125000, 2)
%timeit df2['Check']=df.date.apply(lambda x: x.month==10).map({True:0,False:1})
1 loops, best of 3: 2.56 s per loop
%timeit df2['date'] = np.where(df['date'].dt.month==10,0,1)
10 loops, best of 3: 80.5 ms per loop
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.