Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. import pandas as pd
  2.  
  3. data = {'year': [2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012],
  4. 'team': ['Bears', 'Bears', 'Bears', 'Packers', 'Packers', 'Lions', 'Lions', 'Lions'],
  5. 'wins': [11, 8, 10, 15, 11, 6, 10, 4],
  6. 'losses': [5, 8, 6, 1, 5, 10, 6, 12]}
  7. football = pd.DataFrame(data)
  8. football
  9. # year team wins losses
  10. # 0 2010 Bears 11 5
  11. # 1 2011 Bears 8 8
  12. # 2 2012 Bears 10 6
  13. # 3 2011 Packers 15 1
  14. # 4 2012 Packers 11 5
  15. # 5 2010 Lions 6 10
  16. # 6 2011 Lions 10 6
  17. # 7 2012 Lions 4 12
  18.  
  19.  
  20. # การเลือก 1 Column จะได้ข้อมูลออกมาเป็น Series
  21.  
  22. football['year']
  23. football.year # shorthand for football['year']
  24. # 0 2010
  25. # 1 2011
  26. # 2 2012
  27. # 3 2011
  28. # 4 2012
  29. # 5 2010
  30. # 6 2011
  31. # 7 2012
  32. # Name: year, dtype: int64
  33.  
  34. # การเลือกหลาย Columns จะได้ข้อมูลออกมาเป็น DataFrame
  35.  
  36. football[['year', 'wins', 'losses']]
  37. # year wins losses
  38. # 0 2010 11 5
  39. # 1 2011 8 8
  40. # 2 2012 10 6
  41. # 3 2011 15 1
  42. # 4 2012 11 5
  43. # 5 2010 6 10
  44. # 6 2011 10 6
  45. # 7 2012 4 12
  46.  
  47.  
  48. # การเลือก Row สามารถทำได้หลายวิธี
  49.  
  50. # ระบุ Index โดยใช้ฟังก์ชั่น iloc หรือ loc
  51. football.iloc[[0]]
  52. football.loc[[0]]
  53. # year team wins losses
  54. # 0 2010 Bears 11 5
  55.  
  56. # ใช้การทำ Slicing
  57. football[3:5]
  58. # year team wins losses
  59. # 3 2011 Packers 15 1
  60. # 4 2012 Packers 11 5
  61.  
  62. # ใช้การทำ Boolean Indexing
  63. football[football.wins > 10]
  64. # year team wins losses
  65. # 0 2010 Bears 11 5
  66. # 3 2011 Packers 15 1
  67. # 4 2012 Packers 11 5
  68.  
  69. football[(football.wins > 10) & (football.team == "Packers")]
  70. # year team wins losses
  71. # 3 2011 Packers 15 1
  72. # 4 2012 Packers 11 5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement