02.数据导入&清理

2018-07-01  本文已影响0人  李慕玄

1.导入csv文件

read_csv(file, encoding)
#如导入中文:encoding='utf-8'
from pandas import read_csv
df = read_csv(
    '/users/bakufu/desktop/4.1/1.csv',
    encoding='utf-8'
)

df
Out[173]: 
   age  name
0   23   KEN
1   32  John
2   25  JIMI

2.导入文本文件

read_table(file, names=[列名1, 列名2, ...], sep="", encoding)
#如导入中文:encoding='utf-8'
参数 注释
file 文件路径
names 列名,默认为文件第一行
sep 分隔符,默认为空,表示默认导入为一列
encoding 设置文件编码
from pandas import read_table
df = read_table(
    '/users/bakufu/desktop/4.1/2.txt',
    names=['age', 'name'],
    sep=',',
    encoding='utf-8'        
)

df
Out[175]: 
  age  name
0  23   KEN
1  32  John
2  25  JIMI
3  中文    英文

3.导入EXCEL文件:

read_excel(fileName, sheetname, names)
#如导入中文:encoding='utf-8'

用pandas读取Excel文件时,
如提示:ModuleNotFoundError: No module named 'xlrd',
因为Excel需要单独安装xlrd模块进行支持。

conda list xlrd
参数 注释
fileName 文件路径
sheetname 表名
names 列名,默认为文件中的第一行
from pandas import read_excel
df = read_excel(
    '/users/bakufu/desktop/4.1/3.xlsx',
    sheetname = 'data',
    encoding='utf-8'
)

df
Out[177]: 
   age  name
0   23   KEN
1   32  John
2   25  JIMI

4.解决中文路径异常问题

df = read_excel(
    ...
    encoding='utf-8',
    engine='python'    
)

5.导出csv文件

to_csv(filePath, sep=",", index = TRUE, header = TRUE)
参数 注释
filePath 导出的文件路径
sep 分隔符,默认为逗号
index 是否导出行序号,默认为TRUE
header 是否导出列名,默认为TRUE
from pandas import DataFrame
df = DataFrame({
    'age': [21, 22, 23],
    'name': ['Aa', 'Bb', 'Cc'],
    'sex': ['F', 'F', 'M']        
})

df.to_csv(
    "/users/bakufu/desktop/4.1/df.csv",
    index = False        
)

6.重复值处理

drop_duplicates()

把数据结构中,行相同的数据只保留一行

from pandas import read_csv
df = read_csv('/users/bakufu/desktop/4.3/data.csv')
Out[2]: 
        id   key          value
0  1251147    品牌          Apple
1  1251147  商品名称  苹果iPad mini 3
2  1251147  商品毛重         0.61kg
3  1251147  商品产地             中国
4  1251147    品牌          Apple
5  1251147  商品名称  苹果iPad mini 3
6  1251147    硬盘           128G
7  1251147    尺寸      7.8英寸-9英寸

#找出行重复的位置
dIndex = df.duplicated(['id', 'key', 'value'])
dIndex
Out[4]: 
0    False
1    False
2    False
3    False
4     True
5     True
6    False
7    False
dtype: bool

#根据返回值,将重复值提取出来
df[dIndex]
Out[5]: 
        id   key          value
4  1251147    品牌          Apple
5  1251147  商品名称  苹果iPad mini 3

#根据所有列在原数据直接删除重复值
df = df.drop_duplicates()
Out[7]: 
        id   key          value
0  1251147    品牌          Apple
1  1251147  商品名称  苹果iPad mini 3
2  1251147  商品毛重         0.61kg
3  1251147  商品产地             中国
6  1251147    硬盘           128G
7  1251147    尺寸      7.8英寸-9英寸

#保持原数据不变,将去重的数据赋值给新的变量
newDF = df.drop_duplicates()
Out[9]: 
        id   key          value
0  1251147    品牌          Apple
1  1251147  商品名称  苹果iPad mini 3
2  1251147  商品毛重         0.61kg
3  1251147  商品产地             中国
6  1251147    硬盘           128G
7  1251147    尺寸      7.8英寸-9英寸

#可以指定某n列,删除重复值
df
Out[14]: 
        id   key          value
0  1251147    品牌          Apple
1  1251147  商品名称  苹果iPad mini 3
2  1251147  商品毛重         0.61kg
3  1251147  商品产地             中国
4  1251147    品牌          Apple
5  1251147  商品名称  苹果iPad mini 3
6  1251147    硬盘           128G
7  1251147    尺寸      7.8英寸-9英寸

newDF = df.drop_duplicates(['id', 'key', 'value'])
Out[16]: 
        id   key          value
0  1251147    品牌          Apple
1  1251147  商品名称  苹果iPad mini 3
2  1251147  商品毛重         0.61kg
3  1251147  商品产地             中国
6  1251147    硬盘           128G
7  1251147    尺寸      7.8英寸-9英寸

7.缺失值处理

from pandas import read_csv
df = read_csv(
        '/users/bakufu/desktop/4.4/data.csv'
)
Out[21]: 
        id   key          value
0  1251147    品牌          Apple
1  1251147  商品名称  苹果iPad mini 3
2  1251147  商品毛重            NaN
3  1251147   NaN             中国
4  1251147    硬盘           128G
5  1251147    尺寸      7.8英寸-9英寸

#找出空值的位置
isNA = df.isnull()
Out[23]: 
      id    key  value
0  False  False  False
1  False  False  False
2  False  False   True
3  False   True  False
4  False  False  False
5  False  False  False

#获取出空值所在的行
df[isNA.any(axis=1)]
Out[25]: 
        id   key value
2  1251147  商品毛重   NaN
3  1251147   NaN    中国

df[isNA[['key']].any(axis=1)]
Out[26]: 
        id  key value
3  1251147  NaN    中国

df[isNA[['key', 'value']].any(axis=1)]
Out[27]: 
        id   key value
2  1251147  商品毛重   NaN
3  1251147   NaN    中国

#将NaN值换成指定值
df.fillna('未知')
Out[28]: 
        id   key          value
0  1251147    品牌          Apple
1  1251147  商品名称  苹果iPad mini 3
2  1251147  商品毛重             未知
3  1251147    未知             中国
4  1251147    硬盘           128G
5  1251147    尺寸      7.8英寸-9英寸

#直接删除空值,并赋值给新变量
newDF = df.dropna()
Out[31]: 
        id   key          value
0  1251147    品牌          Apple
1  1251147  商品名称  苹果iPad mini 3
4  1251147    硬盘           128G
5  1251147    尺寸      7.8英寸-9英寸

8.空格值处理

from pandas import read_csv
df = read_csv(
    '/users/bakufu/desktop/4.5/data.csv'
)
Out[33]: 
   id        name
0   1         KEN
1   2      JIMI  
2   3        John

#清除字符串两边空格
newName = df['name'].str.strip()
Out[42]: 
0     KEN
1    JIMI
2    John
Name: name, dtype: object

#清除字符串左边空格
newName = df['name'].str.lstrip()
Out[35]: 
0       KEN
1    JIMI  
2      John
Name: name, dtype: object

#清除字符串右边空格
newName = df['name'].str.rstrip()
Out[40]: 
0         KEN
1        JIMI
2        John
Name: name, dtype: object
上一篇 下一篇

猜你喜欢

热点阅读