[英]How to add a column in pandas with the value depending on the date
I am trying to digitise my portfolio.我正在尝试将我的投资组合数字化。 I have a dataframe
with the daily stock closing information since a certain period (01-01-2020)
and I want to add a column showing how many of the stocks I am holding, so for example on 01-01-2020
, I have zero APPL and from 25-06-2020
I have 2 and from 01-09-2021
I have 1.我有一个dataframe
,其中包含自某个时期(01-01-2020)
以来的每日股票收盘信息,我想添加一列显示我持有的股票数量,例如在01-01-2020
,我有零25-06-2020
,从 2020 年 6 月 25 日开始,我有 2 个,从01-09-2021
年 1 月 9 日开始,我有 1 个。
I have another dataframe
that keeps track of the balance of my stocks when it changes (but not the dates in between).我还有另一个dataframe
可以在我的股票余额发生变化时跟踪它(但不是两者之间的日期)。 This looks like this for this example;这个例子看起来像这样;
Date Balance
25-06-2020 2
01-09-2021 1
I know that df['balance'] = 0
will add a column that is all zero but how can I add conditions based on the date?我知道df['balance'] = 0
将添加一个全为零的列,但是如何根据日期添加条件?
In summary, I have this总之,我有这个
Date Price
01-01-2020 $100
01-02-2020 $100
...
25-06-2020 $120
26-06-2020 $130
...
01-09-2021 $145
02-09-2021 $146
and I want to get to this我想做到这一点
Date Price Balance
01-01-2020 $100 0
01-02-2020 $100 0
...
25-06-2020 $120 2
26-06-2020 $130 2
...
01-09-2021 $145 1
02-09-2021 $146 1
If possible specify first values of Balance
in dictionary is possible use Series.map
with forward filling missing values:如果可能的话,可以使用Balance
在字典中指定第一个值,并使用Series.map
向填充缺失值:
d = {'01-01-2020':0,'25-06-2020':2,'01-09-2021':1}
df['Balance'] = df['Date'].dt.strftime('%Y-%m-%d').map(d).ffill().astype(int)
EDIT: Use left join for new column Balance
, then forward filling values after df1['Date']
, first replace by 0
:编辑:对新列使用左连接Balance
,然后在df1['Date']
之后转发填充值,首先替换为0
:
df['Date'] = pd.to_datetime(df['Date'])
df1['Date'] = pd.to_datetime(df1['Date'])
df2 = df.merge(df1[['Date','Balance']], on='Date', how='left')
df2['Balance'] = df2['Balance'].ffill().fillna(0).astype(int)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.