Pandas (2) - DataFrame

6715 ワード

DataFrame

  • pandas
    -シリーズ:1 Dアレイ、Vector
    -DataFrame:Matrix
  • 2 Dアレイ
  • Data Frameの作成
    ①ディックシーケンスを使用して生成する場合、ディックシーケンスはリスト値とする
    ②Numpyモジュールで作成
    ③read csv()、read excel()関数で生成
    Ex.①ディックシーケンスを使用して作成
    ```
    import numpy as np
    import pandas as pd 
    from pandas import Series, DataFrame
    import matplotlib.pyplot as plt
    # ---------------------------------------------------------------
    df_dic = {
    	'state':['Ohio','Ohio', 'Ohio','Nevada','Nevada','Nevada'],
        'year': [2000,   2001,   2002,   2001,   2002,   2003],
        'pop': [ 1.5,   1.7,    3.6,    2.4,    2.9,    3.2]    
    }
    dicDf=DataFrame(df_dic)       # 생성
    type(dicDf.state)             # <class 'pandas.core.series.Series'>
    ```    
    Ex.②Numpyモジュールの使用
    ```
    df2 = DataFrame(np.random.randint(10, 100, 16).reshape(4, 4), 
    				columns = list('abcd'),
    				index = list('abcd'))
    # 컬럼 값들을 ALL 수정 .... columns // 원본이 바로 반영된다.
    df2.columns = ['one', 'two', 'three', 'four']
    df2
    ```        
    ファイルを読み込んでdfを作成する
    ```
    df3 = pd.read_csv('../dataset/tips.csv')
    ```            
  • DataFrame構造の確認
    ① index
    ② columns
    ③ values
    ④ T
    ファイルを読み込んでdfを作成する
    ```
    data1= {
    	'name' : ['James', 'Tom', 'Jane', 'Peter'],
    	'address' : ['NY', 'Texas', 'NY', 'LA'],
    	'age' : [33, 44, 55, 66]
    }
    df1 = DataFrame(data1) 
    # -----------------------------------------------
    print(df1.index)
    print(df1.columns)
    print(df1.values)
    print(df1.T)
    ```     
    出力値
    ```
    RangeIndex(start=0, stop=4, step=1)                   # df1.index
    Index(['name', 'address', 'age'], dtype='object')     # df1.columns
    [['James' 'NY' 33]
     ['Tom' 'Texas' 44]
     ['Jane' 'NY' 55]
     ['Peter' 'LA' 66]]									  # df1.values
     0      1     2      3								  # df1.T
    name     James    Tom  Jane  Peter
    address     NY  Texas    NY     LA
    age         33     44    55     66
    ```
  • DataFrameクエリー関数
    ①head():前からクエリー、default 5個
    ②tail():後から問い合わせ、default 5個
    ③describe():各列の要約統計を提供し、数字の列について提供します.(count, mean, std, min, 25%, 50%, 75%, max)
    ④info():各欄の情報を表示
    ⑤value counts():特定の列のデータがどのように分布しているかを決定する
    Ex.
    ```
    df3.head()
    df3.tail()
    df3.describe()
    df3.describe(inclue = 'object')    # 카테고리 column정보 요약
    df3.info()
    df3['day'].value_counts()
    ```       
  • DataFrameタイプ変更
    -astype():元のファイルに直接反映されず、再入力が必要です
    Ex.
    ```
    df3['total_bill'].astype('int')
    df3['total_bill'].astype(np.int32)
    df3['total_bill'] = df3['total_bill'].astype(np.int32)
    ```      
  • DataFrameソート
    -sort index():indexでソートされ、昇順=Trueはdefault(ほとんど使用されません)
    -sort values():値順、昇順=Trueがdefault
    Ex. sort_values()
    ```
    # tip을 기준으로 정렬
    df3.sort_values(by = 'tip')
    # -------------------------------------------
    # 기준을 여러 개 줄 수 있음 (list형태로)
    df3.sort_values(by = ['tip', 'total_bill'])
    # -------------------------------------------
    # 기준에 따라 ascending 값을 다르게 줄 수 있음
    df3.sort_values(by = ['day', 'tip'], ascending=[False, True])
    ```      
  • DataFrameカラム名の変更と追加、削除
    ①columns:原本が変更され、全ての修正でよく使われる
    ②rename:オリジナルはすぐに反映されず、再入力またはinplace=Trueが必要となり、一部の修正でよく使用される
    Ex. columns
    ```
    df2.columns = ['python', 'da', 'deep', 'django']
    ```      
    Ex. rename
    ```
    df1_new = df1.rename(columns={'address':'addr'})         # df1의 address column명을 addr로 변경, 재대입
    df1.rename(columns={'address':'addr'}, inplace = True)   # df1의 address column명을 addr로 변경, inplace 속성
    ```      
    Ex.列の追加
    ```
    df1['phone'] = np.nan  # phone column 추가 , 그 안 값들은 NaN
    ```   
  • DataFrame loc
    -DataFrameでnumpyのスライスメソッドがxで動作する
    - df.loc[行条件、列条件]:後のすべての要素を含む
    -条件フィルタ
    Ex.locにスライス
    ```
    import numpy as np
    import pandas as pd 
    from pandas import Series, DataFrame
    import matplotlib.pyplot as plt
    # -------------------------------------
    tips =pd.read_csv('../dataset/tips.csv')
    tips.loc[:6, :'smoker']    # index 6과 'smoker' column도 포함되어 slicing
    ```
    Ex.フィルタ条件
    ```
    condition = (tips['tip'] > 2)     # tip 값을 2불보다 더 많이 지불한 사람들의 데이터만 가져오기
    tips.loc[condition]
    # --------------------------------
    # ------- 조건 여러 개도 가능 ------
    condition1 = (tips['tip'] >= 2)
    condition2 = (tips['sex'] == 'Male')
    condition3 = (tips['size'] == 2)
    tips.loc[condition1 & condition2 & condition3]
    tips.loc[condition1 & condition2 & condition3, 'total_bill':'tip']   # 조건1, 2, 3을 충족시키는 값 중 total_bill과 tip column만 보겠다
    tips.loc[condition1, 'tip'] = 2   # 조건 1을 만족시키는 값들의 tip 값을 다 2로 변경
    ```
  • DataFrame iloc
    -locとは異なり、label検索は使用できません.indexアクセスは無条件です.
    Ex. iloc
    ```
    tips.iloc[:2, [1, 3, 5]]
    ```    
  • DataFrame at/iat
    -値を抽出
    Ex. at/iat
    ```
    tips.at[3, 'day']
    tips.iat[3, 4]
    ```    
  • DataFrame where
    -Condition T/Fによって判断される式
    -条件を満たさない要素に値を割り当てる
    Ex. where
    ```
    tips['tip'].where(tips['tip'] >= 2, 0)    # tip 값이 2 이상인 경우는 냅두고, 만족하지 못하면 0으로 변경
    ```        
  • DataFrame isin
    -pythonのin関数と同じ
    Ex. isin
    ```
    sample = DataFrame({
    	'name': ['강씨', '이씨', '박씨'],
    	'age' : [33, 44, 55]
    })
    cond = sample['name'].isin(['강씨', '이씨'])
    sample.loc[cond]                # 조건에 해당하는 값만 출력
    ```        
  • DataFrame copy
    -元のファイルが破損しないようにデータフレームコピーを作成します.
    Ex. isin
    ```
    tips_copy = tips.copy()
    ```