0

I have a data frame with my stock portfolio. I want to be able to add a stock to my portfolio on streamlit. I have text input in my sidebar where I input the Ticker, etc. When I try to add the Ticker at the end of my dataframe, it does not work.

ticker_add = st.sidebar.text_input("Ticker")

df['Ticker'][len(df)+1] = ticker_add

The code [len(df)+1] does not work. When I try to do [len(df)-1], it works but I want to add it to the end of the dataframe, not replace the last stock. It seems like it can't add a row to the dataframe.

CypherX
  • 7,019
  • 3
  • 25
  • 37
Louis
  • 187
  • 1
  • 3
  • 15
  • Does your dataframe have only one column: `Ticker`? Or, do you have other columns as well? – CypherX Nov 06 '20 at 14:04
  • 1
    If your dataframe's length in `N` and you are trying to add a new row to it, that you can do a simple search on stackoverflow for. This problem, in my opinion has nothing to do with streamlit. Streamlit is just getting you the value of `ticker_add`. The next step is adding this to your existing dataframe as a new row (as I interpret from your code). – CypherX Nov 06 '20 at 14:07

1 Answers1

3

Solution

You MUST first check the type of ticker_add.

type(ticker_add)

Adding new row to a dataframe

  1. Assuming your ticker_add is a dictionary with the column names of the dataframe df as the keys, you can do this:

    df.append(pd.DataFrame(ticker_add))
    
  2. Assuming it is a single non-array-like input, you can do this:

    # adds a new row for a single column ("Ticker") dataframe
    df = df.append({'Ticker': ticker_add}, ignore_index=True)
    

References

  1. Add one row to pandas DataFrame
  2. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html
CypherX
  • 7,019
  • 3
  • 25
  • 37