Home > database >  How to add item last and remove first item in python dataframe?
How to add item last and remove first item in python dataframe?

Time:12-02

My dataframe is like this:

data = {
  "a": [420, 380, 390],
  "b": [50, 40, 45]
}

df = pd.DataFrame(data)

I want to add new item at the end of this dataframe, and remove the first item. I mean cont will be 3 each addition.

New item add

{"a": 300, b: 88}

and last stuation will be:

data = {
  "a": [380, 390, 300],
  "b": [40, 45, 88]
}

Is there a short way to do this?

CodePudding user response:

Using concat:

df = pd.concat([df.iloc[1:],
                pd.DataFrame.from_dict({0: d}, orient='index')], 
               ignore_index=True)

Output:

     a   b
0  380  40
1  390  45
2  300  88

CodePudding user response:

You can use pd.concat because append is getting deprecated. Ref

dct = {"a": 300, "b": 88}
df_new = pd.concat([df, pd.Series(dct).to_frame().T]
                  ).iloc[1:, :].reset_index(drop=True)
print(df_new)

# If maybe the values of 'dict' have multiple items.
# dct = {"a": [300, 400], "b": [88, 98]}
# df_new = pd.concat([df, pd.DataFrame(dct)]
#                   ).iloc[1:, :].reset_index(drop=True)

You can add a new row to df with pandas.DataFrame.append then drop the first-row base number of index. (At the end use reset_index if it is necessary)

dct = {"a": 300, "b": 88}
df_new = df.append(dct, ignore_index=True).drop(0, axis=0).reset_index(drop=True)
print(df_new)

Output:

     a   b
0  380  40
1  390  45
2  300  88

CodePudding user response:

You can append new row to existing dataframe by df.append(). In your example, this would be

new_row = {"a": 300, "b": 88}
df2 = df.append(new_row, ignore_index=True)

(Notice that append works both for Dataframe and dict objects, but the later requires ignore_index=True.

And you can remove the first row from dataframe by one of the following methods:

  1. Select using iloc
df3 = df2.iloc[1:, :]

This slices all rows but the first one, and all columns.

  1. Use drop to remove the first row.
df3 = df2.drop(df.index[0], axis=0, inplace=False)

Or you could use inplace=True to modify df2 inplace, None will be returned in that case.

  • Related