[英]Python Pandas dataframe - add a new column based on index value
I have a Python pandas dataframe that looks like this:我有一个 Python pandas dataframe 看起来像这样:
year_2000 year_1999 year_1998 year_1997 year_1996 year_1995 (MANH, stock name)
MANH 454.47 -71.90 nan nan nan nan TEST
LH 385.52 180.95 -24.14 -41.67 -68.92 -26.47 TEST
DGX 373.33 68.04 4.01 nan nan nan TEST
SKX 306.56 nan nan nan nan nan TEST
where the stock tickers are the index.其中股票代码是指数。 I want to add the name of each stock as a new column
我想将每只股票的名称添加为新列
I tried adding the stock name column via yearly_best['MANH','stock name']='TEST'
but it adds the same name in all rows.我尝试通过
yearly_best['MANH','stock name']='TEST'
添加股票名称列,但它在所有行中添加了相同的名称。
I have a dictionary called ticker_name which contains the tickers and the names我有一本名为ticker_name 的字典,其中包含代码和名称
Out[65]:
{'TWOU': '2U',
'MMM': '3M',
'ABT': 'Abbott Laboratories',
'ABBV': 'AbbVie Inc.',
'ABMD': 'Abiomed',
'ACHC': 'Acadia Healthcare',
'ACN': 'Accenture',
'ATVI': 'Activision Blizzard',
'AYI': 'Acuity Brands',
'ADNT': 'Adient',
thus I would like to get the names from the dict and put then in a column in the dataframe.因此,我想从字典中获取名称,然后将其放入 dataframe 的列中。 How can I do that?
我怎样才能做到这一点?
As the key of your dictionnary are index of your dataFrame you can try:由于您的字典的键是您的 dataFrame 的索引,您可以尝试:
d = {'TWOU': '2U',
'MMM': '3M',
'ABT': 'Abbott Laboratories',
'ABBV': 'AbbVie Inc.',
'ABMD': 'Abiomed',
'ACHC': 'Acadia Healthcare',
'ACN': 'Accenture',
'ATVI': 'Activision Blizzard',
'AYI': 'Acuity Brands',
'ADNT': 'Adient',}
df['stock name'] = pd.Series(d)
You can try:你可以试试:
# Create a new column "stock_name" with the index values
yearly_best['stock_name'] = yearly_best.index
# Replace the "stock_name" values based on the dictionary
yearly_best['stock_name'].map(ticker_name, inplace=True)
Note that in this case, the dataframe's indices will remain as they were (stock tickers).请注意,在这种情况下,数据框的索引将保持原样(股票代码)。 If you would like to replace the indices with row numbers, consider using
reset_index
如果您想用行号替换索引,请考虑使用
reset_index
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.