Home > Net >  Pandas dataframe throwing error when appending to CSV
Pandas dataframe throwing error when appending to CSV

Time:11-02

`

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!

CodePudding user response:

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)

CodePudding user response:

You can use this:

df = df.append({"Col2": 100}, ignore_index=True)
  • Related