Search code examples
pythonpandasdataframecsvexport-to-csv

Pandas dataframe throwing error when appending to CSV


`

import pandas as pd

df = pd.read_csv("stack.csv")

sector_select = "Col2"

df[sector_select] = ["100"]

df.to_csv("stack.csv", index=False, mode='a', header=False)

`

stack.csv has no data other than a header: Col1,Col2,Col3,Col4,Col5

ValueError: Length of values (1) does not match length of index (2)

Im just trying to make a program where I can select a header and append data to the column under that header

You can only run it twice until it gives an error!


Solution

  • That code runs for me.

    But I assume that you would like to run something like this:

    import pandas as pd
    
    df = pd.read_csv("stack.csv")
    
    sector_select = "Col2"
    
    df.at[len(df), sector_select] = "100"
    
    df.to_csv("stack.csv", index=False)