0

I am trying to add a new row to a dataframe. I know that it is usually done with dataframe.append() method but it will not work for my case. Why it does not work is because the user can read any csv file he/she uploads to my app so I have no idea how the dataframe looks like. In psuedo code I did something like this:

  1. User uploads a csv file
  2. I parse through it and I display it on a website
  3. The user clicks on a button to add new row and is redirected to a website where it dynamically generates text fields to type in the information for the new row. The field is generated depending on numbers of columns the dataframe has:
for headers in df.columns.values.tolist() 
#generate field with name header
<input type="text" class="form-control" name="{{headers}}" placeholder="{{headers}}"></input>
  1. The user then types in the values for the new row and clicks "add button"
  2. I can then loop through all values the user typed in.
  3. I add new row depending with these values.

When I loop through the values I append them in a list so I get all values in a list like that:

['PPIQ.SQU900025', 'PPI output index - All industries', '2020.06', '1183', '1184']

I did everything but the last thing is to add new row to the dataframe based on the list above. How can I add these values to a new row? I have been searching but can't make it work.. Please help. I am using flask.

Here is a picture of how I display my data and how to add new row: display data add row

0

2 Answers 2

2

You can turn the list into a data frame and use concat to join it to the original one.

Suppose the original DataFrame is stored in df and that you have the new data stored in new.

# List of new values
new = ['PPIQ.SQU900025', 'PPI output index - All industries', '2020.06', '1183', '1184']
# New data as pandas.DataFrame
new = pd.DataFrame(columns=df.columns, data=[new])
# Overwrite original dataframe
df = pd.concat([df, new], axis=0)
1

You can still use append if you create a new DataFrame from the new data.

df = df.append(
    pd.DataFrame(
        index=(df.index.max()+1,),
        columns=df.columns,
        data=(new_data,),
    )
)

This does not validate anything so if you pass less columns of data, an exception will be thrown. You have to validate data beforehand.

Not the answer you're looking for? Browse other questions tagged or ask your own question.