Home > Enterprise >  how to add the column values to the next row of the same column in pandas
how to add the column values to the next row of the same column in pandas

Time:12-22

how to add the column values to the next row of the same column in pandas

how to update how to add/update the column values to the next row of the same column in pandas image attached for your refence(here i want to update till the next value available)

CodePudding user response:

df = pd.DataFrame({'Col_1':['A','B','C'], 'Col_2':[1,2,3]})
df
###
  Col_1  Col_2
0     A      1
1     B      2
2     C      3

If you wanna insert values to specific index location,

new_row = pd.DataFrame({'Col_1':'D', 'Col_2':4}, index=[1])
df = pd.concat([df.iloc[:1], new_row, df.iloc[1:]]).reset_index(drop=True)
df
###
  Col_1  Col_2
0     A      1
1     D      4 ⬅
2     B      2
3     C      3



If you wanna append values to the last/bottom,

bot_row = ['E', 5]
df = pd.concat([df, pd.DataFrame([bot_row], columns=df.columns)]).reset_index(drop=True)
df
###
  Col_1  Col_2
0     A      1
1     D      4
2     B      2
3     C      3
4     E      5 ⬅



If you wanna update specific row,

df.loc[3] = ['F',6]
df
###
  Col_1  Col_2
0     A      1
1     D      4
2     B      2
3     F      6 ⬅
4     E      5



If you wanna update a specific cell,

df.loc[2, 'Col_1'] = 'G'
df
###
  Col_1  Col_2
0     A      1
1     D      4
2   → G ←    2
3     F      6
4     E      5

CodePudding user response:

If you want to fill empty rows with the last occuring value until the next value occurs, please have a look at this question: How to replace NaNs by preceding or next values in pandas DataFrame?

  • Related