本文案例:
>>> 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)