Advertisement
Guest User

Untitled

a guest
Jun 17th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. a1 b1 a2 b2
  2. 1 2 3 4
  3. 5 6 7 8
  4.  
  5. c d
  6. 1 2
  7. 5 6
  8. 3 4
  9. 7 8
  10.  
  11. import pandas as pd
  12. import numpy as np
  13.  
  14. df = pd.DataFrame(np.arange(1, 9).reshape((2, 4)),
  15. columns=["a1", "b1", "a2", "b2"])
  16.  
  17. part1 = df.iloc[:,0:2]
  18. part2 = df.iloc[:,2:4]
  19.  
  20. new_columns = ["c", "d"]
  21. part1.columns = new_columns
  22. part2.columns = new_columns
  23.  
  24. print pd.concat([part1, part2], ignore_index=True)
  25.  
  26. c d
  27. 0 1 2
  28. 1 5 6
  29. 2 3 4
  30. 3 7 8
  31.  
  32. import pandas as pd
  33. df = pd.DataFrame({'a1' : pd.Series([1,5]), 'b1' : pd.Series([2,6]), 'a2' : pd.Series([3,7]), 'b2' : pd.Series([4,8])})
  34.  
  35. df1 = df[['a1','b1']]
  36. df2 = df[['a2','b2']]
  37. df1.columns = ['c','d']
  38. df2.columns = ['c','d']
  39. df1.append(df2)
  40.  
  41. # Make data as in previous answers
  42. import pandas as pd
  43. import numpy as np
  44.  
  45. df = pd.DataFrame(np.arange(1, 9).reshape((2, 4)),
  46. columns=["a1", "b1", "a2", "b2"])
  47.  
  48. # Melt both columns and concatenate
  49. df = pd.concat([
  50. df[['a1', 'a2']].melt(value_name='c'),
  51. df[['b1', 'b2']].melt(value_name='d')],
  52. axis=1)
  53.  
  54. # Discard unwanted columns melt creates
  55. df = df[['c', 'd']]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement