Noplatts
Noplatts

Reputation: 45

Inserting a row into a Pandas Dataframe in a certain column (without a name)

I have the following dataframe:

            value1 value2 value3
2021-04-26  22       22    22   
2021-04-27  21       26    26 
2021-04-28  27       29    27 

However, after inserting a new row like:

row: {'value1': 40, 'value2': 40, 'value3': 40}
df.append(row, ignore_index=True)

The date column (even though it doesn't have a label) gets transformed into:

   value1 value2 value3
0  22       22    22   
1  21       26    26 
2  27       29    27 
3  40       40    40

Instead of: (desired output)

            value1 value2 value3
2021-04-26  22       22    22   
2021-04-27  21       26    26 
2021-04-28  27       29    27 
NaN         40       40    40

How can I add a new row with a certain date but without changing the whole dataframe, so I would get my desired output? Any help would be appreciated, thanks!

Upvotes: 3

Views: 80

Answers (2)

gtomer
gtomer

Reputation: 6574

The date is an index. Reset index before appending:

df.reset_index()

Upvotes: 1

perl
perl

Reputation: 9941

You can append it as a DataFrame with np.nan as its index:

row = {'value1': 40, 'value2': 40, 'value3': 40}
df.append(pd.DataFrame([row], index=[np.nan]))

Output:

            value1  value2  value3
2021-04-26      22      22      22
2021-04-27      21      26      26
2021-04-28      27      29      27
NaN             40      40      40

Upvotes: 4

Related Questions