FINLAB

06

Oct 6th, 2019
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.04 KB | None | 0 0
  1. '''
  2. 1. 創建
  3. '''
  4. import pandas as pd
  5.  
  6. #pd.DataFrame({'column name1':list/Series,'column name2':list/Series...})
  7. df1 = pd.DataFrame({'cid':['c01','c02','c03','c04','c05'],'time_spent':[23,41,342,97,456]})
  8.  
  9. #可自訂index
  10. #df1 = pd.DataFrame({'cid':['c01','c02','c03','c04','c05'],'time_spent':[23,41,342,97,456]},index=['a','b','c','d','e'])
  11. df1
  12.  
  13. # JSON list
  14. df3 = pd.DataFrame([{'cid':'c02','num_products':2},{'cid':'c03','num_products':3},{'cid':'c04','num_products':6}])
  15. df3
  16.  
  17. '''
  18. 2. 取值
  19. '''
  20. # get one column
  21. df1['time_spent'] #Series
  22. # 同 df1.time_spent
  23.  
  24. # get multiple columns
  25. df1[['cid','time_spent']] #DataFrame
  26.  
  27. # get rows : [i,j] from index i to index j
  28. df1[0:2]
  29.  
  30. # 根據指定條件取值
  31. df1[df1['time_spent']>100]
  32.  
  33. '''
  34. 3. 新增
  35. '''
  36. # 新增一欄
  37. df1['num_products'] = [2,3,1,6,7]
  38. df1
  39. # 新增列:append DataFrame(若新增的欄位不存在,會自動新增欄位)
  40. df1 = df1.append(pd.DataFrame([{'cid':'c06','time_spent':231,'num_products':3}])).reset_index(drop=True)  
  41. # append後記得要再assign回去
  42. # reset_index(drop=True) 重置index,要不然index會維持新增DataFrame的index(0,1,2,3,4,5,0)
  43. df1
  44.  
  45. '''
  46. 4. 修改
  47. '''
  48. # 修改欄位名稱 : rename(columns = {old column name mapping to new column name})
  49. df1 = df1.rename(columns = {'cid':'pid','num_products':'num_purchase'})
  50. df1
  51. # 修改列內容
  52. df1[0:1] = pd.DataFrame([{'pid':'c07','time_spent':31,'num_purchase':1}])
  53. df1
  54.  
  55. '''
  56. 5. 刪除
  57. '''
  58. # 刪除欄 : del
  59. del df1['pid']
  60. df1
  61. # 刪除欄 : drop(方法2),要特別標注 axis = 1 表示刪除的是欄不是列
  62. df1 = df1.drop('time_spent',axis = 1)
  63. df1
  64. # 列:drop(index list)
  65. df1 = df1.drop([1,2])
  66. df1
  67. # Reset Index
  68. df1 = df1.reset_index(drop=True)
  69. df1
  70.  
  71. '''
  72. 6.合併
  73. pd.merge() 資料對接
  74. pd.concat() 直接合併
  75. '''
  76. df2 = pd.DataFrame({'age':[20,42,25,17,13]})
  77. df2
  78. df3 = pd.concat([df1,df2], axis=1)
  79. df3
  80. df_new = pd.DataFrame({'age':[20,42,14,17,55,13],'price':[400,399,250,150,200,300]})
  81. df_new
  82. df4 = pd.merge(df3, df_new, how='inner', on='age')
  83. df4
Advertisement
Add Comment
Please, Sign In to add comment