如何避免在pandas数据帧上写一个粗大的forloop

2024-04-26 20:28:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个像这样的数据帧:

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})

我想制作第三列,一个布尔值,它说,“对于每个月,开始月份库存==上个月月末的库存水平吗?”在

我可以编写一个fould for循环来实现这一点,但我想知道如何编写一个向量化的动作来实现同样的效果。此外,边缘情况是索引位置0,对于该位置,没有任何可与之比较的开始月份值。在


Tags: 数据importdataframepandasas库存水平end
1条回答
网友
1楼 · 发布于 2024-04-26 20:28:07
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()以便可以将当前行与相邻行进行比较。然后我开始东风九号[0,'parity']=True,因为它没有可与之比较的前导项。在

相关问题 更多 >