0

I have a dataframe below and I want to insert a new row under shop with values, how do I do that ?

values = 0.2, park, false


df1 = 
   number    variable values
1     NaN        bank   True
2     3.0        shop  False
3     0.5      market   True
4     NaN  government   True
5     1.0       hotel   true
Jimmy3421
  • 41
  • 6
  • Does this answer your question? [Appending a list or series to a pandas DataFrame as a row?](https://stackoverflow.com/questions/26309962/appending-a-list-or-series-to-a-pandas-dataframe-as-a-row) – Yevhen Kuzmovych Nov 16 '22 at 11:16
  • I would like it to be added as a row under shop not at the end of the dataframe, variable = shop – Jimmy3421 Nov 16 '22 at 11:25

2 Answers2

1

You can try:

import pandas as pd

df = pd.DataFrame({'number': [float('NaN'), 3.0, 0.5, float('NaN'), 1.0], 'variable':['bank','shop','market','government','hotel'], 'values':[True, False, True, True, True]})
print("----- ORIGINAL ------")
print(df)
shop_index = df.reset_index()['variable'].tolist().index('shop') 
insert = pd.DataFrame({"number": 0.2, "variable": "park", "values": False}, index=[shop_index+1])

df2 = pd.concat([df.iloc[:shop_index+1], insert, df.iloc[shop_index+1:]]).reset_index(drop=True)
print("----- AFTER INSERT ------")
print(df2)

Output:

----- ORIGINAL ------
   number    variable  values
0     NaN        bank    True
1     3.0        shop   False
2     0.5      market    True
3     NaN  government    True
4     1.0       hotel    True


----- AFTER INSERT ------
   number    variable  values
0     NaN        bank    True
1     3.0        shop   False
2     0.2        park   False
3     0.5      market    True
4     NaN  government    True
5     1.0       hotel    True
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61
0

Using indices, you can specify a row to modify using df.loc[] To input

To append to the last row in the current dataframe, get the last index using df.loc[-1], add a new index and sort them.

In your case:

df.loc[-1] = values
df.index = df.index + 1 
df = df.sort_index()