2015-11-07 110 views
-1

像我有一个数据帧写for循环的粗暴:如何避免对大熊猫据帧

import pandas as pd 

begin_month = pd.Series([1, 19, 45, 32, 54]) 
end_month = pd.Series([19,45,32,54,99]) 

inventory = pd.DataFrame({"begin_month":begin_month, "end_month": end_month}) 

我想打第三列,一个布尔值,即说:“每个月,做begin_month清单==上个月的end_month库存水平?“

我可以写for循环,这是否犯规,但我不知道我怎么会写一个量化的行动来实现同样的事情。此外,边缘情况是索引位置0,没有什么可以比较它的begin_month值。

回答

0
import pandas as pd 

begin_month = pd.Series([1, 19, 145, 32, 54]) 
end_month = pd.Series([19,45,32,54,99]) 

df = pd.DataFrame({"begin_month":begin_month, "end_month": end_month}) 

df['parity'] = df['begin_month'] == df['end_month'].shift() 
df.ix[0,'parity'] = True 

print df 

关键是要使用.shift(),以便您可以将当前行与相邻行进行比较。我设置了df.ix [0,'parity'] = True,因为它没有前置任务来比较它。

+0

请给你的答案添加一些解释。 – Haris

+1

@哈里斯我补充说明的情况下,答案是不言自明的。 – user3556757