Home > Blockchain >  how do I insert a row for under a specific cell value
how do I insert a row for under a specific cell value

Time:11-17

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

CodePudding user response:

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()

CodePudding user response:

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
  • Related