我有一个dataframe (df),其中包含10列公司股票价格和相关数据。索引有许多不同的日期,但是有多个相同的日期(它是按日期排序的)。此外,此问题的重要列是df“cond1”和df“cond2”和df“‘Returns”。
这是一个只有2个索引值(1/21/2017和1/22/2017)的3列数据的例子,实际上有多个日期和多个变量,等等。
Name Cond1 Cond2 Returns
1/21/2017 Apple 2 4 0.052450819
1/21/2017 Blackberry 6 5 0.423446578
1/21/2017 Microsoft 3 2 0.073850562
1/21/2017 IBM 1 1 0.966576931
1/21/2017 Ubisoft 5 7 0.371786953
1/21/2017 Next 4 3 0.58357725
1/21/2017 Marks and Spencer 2 7 0.466737922
1/21/2017 Alpha 4 3 0.291305661
1/21/2017 Right move 6 2 0.206502435
1/21/2017 Topsy 7 5 0.655331635
1/21/2017 Pizza hut 4 7 0.295723144
1/21/2017 Mcdonalds 3 4 0.338535647
1/22/2017 IBM 2 3 0.975326708
1/22/2017 Next 1 5 0.70893239
1/22/2017 Alpha 1 3 0.362154048
1/22/2017 Blackberry 6 2 0.664525792
1/22/2017 Apple 6 6 0.363531989现在我想创建两个列'Returns2‘和'Returns3’
Returns 2= dataframe中的新列,如果Cond1 < Cond2,则该列仅显示该特定公司的日期和12个期间的回报。
Returns 3= dataframe中的新列,如果为Cond1,则该列仅显示该特定公司提前1天和从该日起的12个期间的退货
因此,最终我希望该公司在12天内连续12次退货,满足Cond1的要求
发布于 2017-01-31 06:41:00
你可以这样做:
df = df.set_index('Name', append=True).swaplevel().sort_index()
df.loc[df.Cond1< df.Cond2, 'returns2'] = True
df.returns2 = df.groupby(level=0).returns2.transform(lambda x: x.ffill(limit=12))
df.returns2 = df.returns2.mask(df.returns2.notnull(), df.Returns)
df.returns2
Name
Alpha 2017-01-21 NaN
2017-01-22 0.362154
Apple 2017-01-21 0.0524508
2017-01-22 0.363532
Blackberry 2017-01-21 NaN
2017-01-22 NaN
IBM 2017-01-21 NaN
2017-01-22 0.975327
Mcdonalds 2017-01-21 0.338536
Microsoft 2017-01-21 NaN
MnSpencer 2017-01-21 0.466738
Next 2017-01-21 NaN
2017-01-22 0.708932
Pizzahut 2017-01-21 0.295723
Rightmove 2017-01-21 NaN
Topsy 2017-01-21 NaN
Ubisoft 2017-01-21 0.371787
Name: test, dtype: objecthttps://stackoverflow.com/questions/41945383
复制相似问题