简体   繁体   English

使用基于数据框年份的值向数据框添加新列

[英]Adding new column to data frame with values based on years of data frame

I have a dataframe我有一个 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)

Output is, Output 是,

在此处输入图像描述

I wanted to add column "deb/eq" to this dataframe and I want to add values specific to year.我想在 dataframe 中添加列“deb/eq”,并且我想添加特定于年份的值。

For eg.例如。

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

How can I add new column and values to dataframe based on dataframes year?如何根据数据帧年份向 dataframe 添加新列和值?

Use Index.map with set not matched values ( NaN s) to 2.0 by Index.fillna :使用Index.map并通过Index.fillna将不匹配的值( NaN s)设置为2.0

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

With numpy.select :使用numpy.select

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

EDIT:编辑:

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

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

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