使用基于Dataframe年份的值向Dataframe添加新列

pkln4tw6  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(377)

我有一个Dataframe

import pandas_datareader as webreader
import math 
import numpy as np 
import pandas as pd 
from datetime import date, timedelta, datetime
from pandas.plotting import register_matplotlib_converters
import matplotlib.pyplot as plt 
import matplotlib.dates as mdates
from sklearn.metrics import mean_absolute_error, mean_squared_error
from keras.models import Sequential 
from keras.layers import LSTM, Dense, Dropout
from keras.callbacks import EarlyStopping
from sklearn.preprocessing import RobustScaler

stockname = 'INFOSYS'
symbol = 'INFY.NS'
df = webreader.DataReader(symbol, start=date_start, end=date_today, data_source="yahoo")
print(df)

输出为,

我想把“deb/eq”列添加到这个数据框中,并且我想添加特定于年份的值。
例如。

for all dates in 2020 - all deb/eq values to be 0.00
for all dates in 2019 - all deb/eq values to be 1.00
for all dates in 2018 and previous - all deb/eq values to be 2.00

如何基于dataframes year向dataframe添加新列和值?

mwecs4sa

mwecs4sa1#

使用 Index.map 设置了不匹配的值( NaN s) 至 2.0Index.fillna :

df['deb/eq'] = df.index.year.map({2020:0.0, 2019:1.0}).fillna(2.0)

numpy.select :

y = df.index.year
df['deb/eq'] = np.select([y == 2020, y == 2019], [0.0, 1.0], default=2.0)

编辑:

df = pd.DataFrame(index=pd.date_range('2003', '2021', freq='A'))

df['ATR'] = df.index.year.map({2021:91.45, 2020:97.53, 2019:92.62, 2018:81.83, 2017:74.21, 2016:74.22, 2015:76.52, 2014:84.11, 2013:85.44, 2012:87.26, 2011:87.97, 2010:81.10, 2009:95.80, 2008:90.86, 2007:101.25, 2006:99.05, 2005:104.12, 2004:92.67}).fillna(0.0)
print (df)
               ATR
2003-12-31    0.00
2004-12-31   92.67
2005-12-31  104.12
2006-12-31   99.05
2007-12-31  101.25
2008-12-31   90.86
2009-12-31   95.80
2010-12-31   81.10
2011-12-31   87.97
2012-12-31   87.26
2013-12-31   85.44
2014-12-31   84.11
2015-12-31   76.52
2016-12-31   74.22
2017-12-31   74.21
2018-12-31   81.83
2019-12-31   92.62
2020-12-31   97.53

相关问题