move_rows.py 817 B

1234567891011121314151617181920212223242526272829303132
  1. # Move rows from one dataframe to another
  2. # https://stackoverflow.com/questions/36142959/pandas-move-rows-from-1-df-to-another-df#36143395
  3. import pandas as pd
  4. data = {'Name':['Tom', 'nick', 'krish', 'jack'], 'Age':[20, 21, 19, 18]}
  5. df = pd.DataFrame(data)
  6. df_from = df.copy()
  7. df_to = pd.DataFrame()
  8. def move(a,b,cond):
  9. rows = a.loc[cond, :]
  10. # b.append acts like pass-by-value, parent not affected
  11. b = b.append(rows, ignore_index=True)
  12. # a.drop acts like pass-by-reference, parent affected
  13. a.drop(rows.index, inplace=True)
  14. return b
  15. # return local copy so it can be assigned in parent
  16. return(b)
  17. df_to = move(df_from,df_to,df_from.Name == "Tom")
  18. df_to = move(df_from,df_to,df_from.Name == "nick")
  19. print("AFTER")
  20. print(f"df_from is {df_from}")
  21. print(f"df_to is {df_to}")
  22. print()