DataFrame數據處理筆記(長期更新)

本文案例:

>>> df = pd.DataFrame([[1, 2.0, 3], [4, 5.0, 6], [7, 8.0, 9]], columns = ['a', 'b', 'c'])
>>> df['a'] = df['a'].astype(str)
>>> df
   a    b  c
0  1  2.0  3
1  4  5.0  6
2  7  8.0  9
>>> df.dtypes
a     object
b    float64
c      int64
dtype: object

DataFrame的數據類型改變

1、單列數據類型改變

方法一:pd.to_numeric()適用於單列

>>> df
   a    b  c
0  1  2.0  3
1  4  5.0  6
2  7  8.0  9
>>> df.dtypes
a     object
b    float64
c      int64
dtype: object
>>> df['a'] = pd.to_numeric(df['a'])
>>> df
   a    b  c
0  1  2.0  3
1  4  5.0  6
2  7  8.0  9
>>> df.dtypes
a      int64
b    float64
c      int64
dtype: object

方法二:df[列名].astype(數據類型)

>>> import numpy as np
>>> df
   a    b  c
0  1  2.0  3
1  4  5.0  6
2  7  8.0  9
>>> df.dtypes
a     object
b    float64
c      int64
dtype: object
>>> df['b'] = df['b'].astype(np.int64)
>>> df.dtypes
a    object
b     int64
c     int64
dtype: object

方法三:df[列名].map(數據類型)

>>> df
   a    b  c
0  1  2.0  3
1  4  5.0  6
2  7  8.0  9
>>> df.dtypes
a     object
b    float64
c      int64
dtype: object
>>> df['a'] = df['a'].map(int)
>>> df.dtypes
a      int64
b    float64
c      int64
dtype: object

2、整體數據類型改變

>>> df
   a    b  c
0  1  2.0  3
1  4  5.0  6
2  7  8.0  9
>>> df.dtypes
a     object
b    float64
c      int64
dtype: object
>>> df = df.astype(np.int64)
>>> df.dtypes
a    int64
b    int64
c    int64
dtype: object

DataFrame的數據選取與刪除

1、選取所需的列

>>> df
   a    b  c
0  1  2.0  3
1  4  5.0  6
2  7  8.0  9
>>> df = df[['a', 'b']]
>>> df
   a  b
0  1  2
1  4  5
2  7  8

2、選取所需的行

方法一:使用&連接多個條件

>>> df
   a    b  c
0  1  2.0  3
1  4  5.0  6
2  7  8.0  9
>>> df
   a    b  c
0  1  2.0  3
1  4  5.0  6
2  7  8.0  9
>>> df[(df['b']>3) & (df['c']>6)]
   a    b  c
2  7  8.0  9

方法二:如果某一列的數據是字符串,則可使用isin(),它的反函數是在其前面加上‘~’。

>>> df
   a    b  c
0  1  2.0  3
1  4  5.0  6
2  7  8.0  9
>>> df[df['a'].isin(['1', '4'])]
   a    b  c
0  1  2.0  3
1  4  5.0  6
>>> df[~df['a'].isin(['1', '4'])]
   a    b  c
2  7  8.0  9

3、刪除某些列

>>> df
   a    b  c
0  1  2.0  3
1  4  5.0  6
2  7  8.0  9
>>> df.drop(columns = ['b', 'c'])
   a
0  1
1  4
2  7

DataFrame的空值統計與處理

1、查看哪些列有空值

方法1:使用isnull()加上any()或者all()

>>> df
     a    b  c
0    1  2.0  3
1  NaN  5.0  6
2    7  8.0  9
>>> df.isnull().all()   # 判斷列的值是否全爲空
a    False
b    False
c    False
dtype: bool
>>> df.isnull().any()  # 判斷列的值是否含有空
a     True
b    False
c    False
dtype: bool

方法二:info()

>>> df
     a    b  c
0    1  2.0  3
1  NaN  5.0  6
2    7  8.0  9
>>> df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
a    2 non-null object
b    3 non-null float64
c    3 non-null int64
dtypes: float64(1), int64(1), object(1)
memory usage: 152.0+ bytes

2、刪除含有空值的行或者列

>>> df
     a    b  c
0    1  2.0  3
1  NaN  5.0  6
2    7  8.0  9
>>> df.dropna(axis=0, how='any')  #  ‘all’表示刪除全爲空值的行
   a    b  c
0  1  2.0  3
2  7  8.0  9
>>> df.dropna(axis=1, how='any')  # ‘all’表示刪除全爲空值的列
     b  c
0  2.0  3
1  5.0  6
2  8.0  9

DataFrame使用apply()

1、單列使用apply()

>>> df
   a    b  c
0  1  2.0  3
1  4  5.0  6
2  7  8.0  9
>>> df.dtypes
a     object
b    float64
c      int64
dtype: object
>>> df['a'] = df['a'].apply(lambda x: x+'New')  # x代表是該列中的一個值
>>> df
      a    b  c
0  1New  2.0  3
1  4New  5.0  6
2  7New  8.0  9

2、整體使用apply()

>>> df
   a    b  c
0  1  2.0  3
1  4  5.0  6
2  7  8.0  9
>>> df.dtypes
a     object
b    float64
c      int64
dtype: object
>>> df['d'] = df.apply(lambda x: x['b']+x['c'], axis=1)  # x相當於是該行內容的一個Series
>>> df
   a    b  c     d
0  1  2.0  3   5.0
1  4  5.0  6  11.0
2  7  8.0  9  17.0

DataFrame使用str()

DataFrame中object類型的列使用str()後可以進行字符操作,如contains()、split()、strip()、findall()、replace()等。

>>> df
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9
>>> df.dtypes
a    object
b     int64
c     int64
dtype: object
>>> df['a'].str.contains('1')
0     True
1    False
2    False
Name: a, dtype: bool
>>> df[df['a'].str.contains('1')]
   a  b  c
0  1  2  3
>>> df['a'] = df['a'].str.replace('4', '4new')
>>> df
      a  b  c
0     1  2  3
1  4new  5  6
2     7  8  9

DataFrame進行獨熱編碼

較簡單的方法pd.get_dummies()

>>> df
   a    b  c
0  1  2.0  3
1  4  5.0  6
2  7  8.0  9
>>> pd.get_dummies(df, columns=['a'])
     b  c  a_1  a_4  a_7
0  2.0  3    1    0    0
1  5.0  6    0    1    0
2  8.0  9    0    0    1

DataFrame的日期操作

1、將任意的object轉換成datatime

使用pd.to_datetime(df, format=’’),format中的格式必須和object數據格式完全匹配,其中%Y爲年,%m爲月,%d爲日,%H爲時,%M爲分,%S爲秒。

>>> df
                   date1                   date2
0  2016-03-7 ## 13:24:56  2017-12-06 ## 23:34:43
1  2017-06-06 ## 12:01:3   2018-04-12 ## 9:32:59
2   2019-09-10 ## 06:6:6    2019-10-1 ## 03:34:3
>>> df.dtypes
date1    object
date2    object
dtype: object
>>> df['date1'] = pd.to_datetime(df['date1'], format='%Y-%m-%d ## %H:%M:%S')
>>> df['date2'] = pd.to_datetime(df['date2'], format='%Y-%m-%d ## %H:%M:%S')
>>> df
                date1               date2
0 2016-03-07 13:24:56 2017-12-06 23:34:43
1 2017-06-06 12:01:03 2018-04-12 09:32:59
2 2019-09-10 06:06:06 2019-10-01 03:34:03
>>> df.dtypes
date1    datetime64[ns]
date2    datetime64[ns]
dtype: object

2、將任意的datatime轉換成任意的object

>>> df
                date1               date2
0 2016-03-07 13:24:56 2017-12-06 23:34:43
1 2017-06-06 12:01:03 2018-04-12 09:32:59
2 2019-09-10 06:06:06 2019-10-01 03:34:03
>>> df.dtypes
date1    datetime64[ns]
date2    datetime64[ns]
dtype: object
>>> df['date3'] = df['date2'].apply(lambda x: x.strftime('%Y/%m/%d'))
>>> df
                date1               date2       date3
0 2016-03-07 13:24:56 2017-12-06 23:34:43  2017/12/06
1 2017-06-06 12:01:03 2018-04-12 09:32:59  2018/04/12
2 2019-09-10 06:06:06 2019-10-01 03:34:03  2019/10/01

3、datetime類型的一些操作

1、通過datetime的dt屬性提取year/month/day/hour/minute/second

>>> df
                date1               date2
0 2016-03-07 13:24:56 2017-12-06 23:34:43
1 2017-06-06 12:01:03 2018-04-12 09:32:59
2 2019-09-10 06:06:06 2019-10-01 03:34:03
>>> df['year'] = df.date2.dt.year
>>> df['month'] = df.date2.dt.month
>>> df
                date1               date2  year  month
0 2016-03-07 13:24:56 2017-12-06 23:34:43  2017     12
1 2017-06-06 12:01:03 2018-04-12 09:32:59  2018      4
2 2019-09-10 06:06:06 2019-10-01 03:34:03  2019     10

2、求兩個日期的間隔天數

>>> df
                date1               date2
0 2016-03-07 13:24:56 2017-12-06 23:34:43
1 2017-06-06 12:01:03 2018-04-12 09:32:59
2 2019-09-10 06:06:06 2019-10-01 03:34:03
>>> df['gap'] = (df['date2']-df['date1'])/ dt.timedelta(days=1)
>>> df
                date1               date2         gap
0 2016-03-07 13:24:56 2017-12-06 23:34:43  639.423461
1 2017-06-06 12:01:03 2018-04-12 09:32:59  309.897176
2 2019-09-10 06:06:06 2019-10-01 03:34:03   20.894410

注:天數除以7、30、356轉換成周,月,年

DataFrame的兩列字符串拼接

首先確保兩列的數據類型是str,可以用map()來轉化數據類型。

>>> df
   a    b  c
0  1  2.0  3
1  4  5.0  6
2  7  8.0  9
>>> df.dtypes
a      int64
b    float64
c      int64
dtype: object
>>> df['d'] = '(' + df['b'].map(str) + ',' + df['c'].map(str) + ')'
>>> df
   a    b  c        d
0  1  2.0  3  (2.0,3)
1  4  5.0  6  (5.0,6)
2  7  8.0  9  (8.0,9)
發佈了62 篇原創文章 · 獲贊 38 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章