简体   繁体   中英

Add series to only the first row in a DataFrame in Python

i have a series of tickers of the S&P500 constituents (ticker). I want to add all the tickers to my DataFrame (SP) within the column Ticker and within the row of the 2021-01-22.

在此处输入图像描述

So just copy all the tickers into one cell, like this:

SP = pd.DataFrame(data={'Date': "2021-01-22", 'Ticker': ['MMM,ABT,ABBV,...','NaN','NaN']})
SP

    Date    Ticker
0   2021-01-22  MMM,ABT,ABBV,...
1   2021-01-22  NaN
2   2021-01-22  NaN

I have tried SP.at[0, 'Ticker'] = ticker , but it did not work.

Ok, you can do this way

ticker_list = list(ticker.values)
SP.iloc[5494,1] = ', '.join(ticker_list)
SP

Here I have just made a list of ticker values and appended it to the row you want. By seeing your image, your row for date '2021-01-22' seems to be 5494.

Create SP Data frame with Date Field

SP = pd.DataFrame(data={'Date': ["2021-01-22","2021-01-21","2021-01-20"]})    

Create Ticker Column with 'NaN' Value

SP['Ticker']='NaN'    

Create Ticker Data frame -

Ticker=pd.DataFrame(['MMM','ABT','ABBV','...','NaN','NaN'])    

Convert Ticker data frame column data into list and assign it to Ticker column in SP data frame

SP['Ticker'][0]=Ticker[0].tolist()  #From Data Frame  

Ticker  = ['MMM','ABT','ABBV','...','NaN','NaN']
SP['Ticker'][0]=Ticker              #From pre-defined list  

display(SP)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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