繁体   English   中英

如何在一段时间内 map 一只股票的特定行业?

[英]How can I map a stock's specific sector over a period of time?

我在一段时间内无法映射特定股票的行业。 给你举个例子。 这是股票的行业数据。

ticker     sector_code   entry_date   exit_date
abc        sec1          20080501     20110504
abc        sec2          20110505     20120403
abc        sec3          20120404     NA

时间段为 01-01-2008 至 01-01-2020。 我想创建一个这样的表:

             abc
2008-01-01   no_sector
...
2008-05-01   sec1
2008-05-02   sec1
...
2011-11-11   sec2
...

我的基本直觉是使用循环和 if 语句。 但我发现它会非常复杂且计算成本很高。 我想不出任何其他方法来做到这一点。 请帮我一把好吗? 非常感谢。

利用:

#convert values to datetimes and replace missing values by another column
df['entry_date'] = pd.to_datetime(df['entry_date'], format='%Y%m%d')
df['exit_date'] = pd.to_datetime(df['exit_date'], format='%Y%m%d').fillna(df['entry_date'])

print (df)
  ticker sector_code entry_date  exit_date
0    abc        sec1 2008-05-01 2011-05-04
1    abc        sec2 2011-05-05 2012-04-03
2    abc        sec3 2012-04-04 2012-04-04

#for each row create date range and concat together
s = pd.concat([pd.Series(r.Index,pd.date_range(r.entry_date, r.exit_date)) 
                          for r in df.itertuples()])

#create new DataFrame and join original data with filtered columns by list
df = (pd.DataFrame(s.index, index=s, columns=['date'])
        .join(df[['ticker','sector_code']])
        .reset_index(drop=True))
print (df)
           date ticker sector_code
0    2008-05-01    abc        sec1
1    2008-05-02    abc        sec1
2    2008-05-03    abc        sec1
3    2008-05-04    abc        sec1
4    2008-05-05    abc        sec1
        ...    ...         ...
1430 2012-03-31    abc        sec2
1431 2012-04-01    abc        sec2
1432 2012-04-02    abc        sec2
1433 2012-04-03    abc        sec2
1434 2012-04-04    abc        sec3

[1435 rows x 3 columns]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM