pandas資料樣本行列選取
阿新 • • 發佈:2019-01-01
注:以下程式碼是基於python3.5.0編寫的
import pandas food_info = pandas.read_csv("food_info.csv") # ------------------選取資料樣本的第一行-------------------- print(food_info.loc[0]) #------------------選取資料樣本的3到6行---------------------- print(food_info.loc[3:6]) #------------------head選取資料樣本的前幾行------------------ print(food_info.head(2)) # ------------------選取資料樣本的2,5,10行,兩種方法----------- # print(food_info.loc[[2,5,10]]) #方法一 two_five_ten = [2,5,10] #方法二 print(food_info.loc[two_five_ten]) # ------------------選取資料樣本的NDB_No列-------------------- # ndb_col = food_info["NDB_No"] #方法一 col_name = "NDB_No"#方法二 ndb_col = food_info[col_name] print(ndb_col) # ------------------選取資料樣本的多列------------------- # zinc_copper = food_info[["Zinc_(mg)", "Copper_(mg)"]] columns = ["Zinc_(mg)", "Copper_(mg)"] zinc_copper = food_info[columns] print(zinc_copper) # ---------------------綜合小例子----------------------------col_names = food_info.columns.tolist() #把所有的行轉化成list print(col_names) gram_columns = [] for c in col_names: #遍歷col_names,找出所有以(g)結尾的位置 if c.endswith("(g)"): gram_columns.append(c) print(gram_columns) gram_df = food_info[gram_columns] #把所有以(g)結尾的列存放到gram_df print(gram_df.head(3)) #列印前3行