原本打算学习pandas模块,并写一个博客记录一下本身的学习,可是不知道怎么了,最近好像有点急功近利,就想把别人的东西复制过来,小心沉下来,本身自觉地将本来写满的pandas学习笔记删除了,此次打算写上本身的学习记录,这里送给本身一句话,同时送给看这篇博客的人,共勉html
当你迷茫的时候,当你饱受煎熬的时候,请停下来,想一想本身学习的初衷,想一想本身写博客的初衷,爱你所爱,行你所行,遵从你心,无问西东。java
好了,正文开始。python
pandas是作数据分析很是重要的一个模块,它使得数据分析的工做变得更快更简单。因为现实世界中数据源的格式很是多,可是pandas也支持了不一样数据格式的导入方法,因此学习pandas很是有必要。mysql
本文首先记录一下本身学习read_csv的笔记,固然了本身须要用什么,就学习什么,而不是记录人家read_csv的全部方法,要是想看全部的方法详解能够去官网,要想学习Pandas建议先看下面2个网站。c++
官网地址以下:https://pandas.pydata.org/sql
官网教程以下(十分钟搞定pandas):https://pandas.pydata.org/pandas-docs/stable/10min.html数据库
NAN (数值数据类型的一类数),全称Not a Number ,表示未定义或者不可表示的值。json
Train_A_001.csv文件内容以下:api
0.916,4.37,-1.372,0.102,0.041,0.069,0.018 0.892,3.955,-1.277,0.015,-0.099,-0.066,0.018 0.908,3.334,-1.193,0.033,-0.098,-0.059,0.018 1.013,3.022,-1.082,0.151,0.015,0.035,0.018 1.111,2.97,-1.103,-0.048,-0.175,-0.171,0.019 1.302,3.043,-1.089,0.011,-0.085,-0.097,0.018 1.552,3.017,-1.052,0.066,-0.002,-0.036,0.019 1.832,2.796,-0.933,0.002,-0.028,-0.075,0.019 2.127,2.521,-0.749,0.011,0.041,-0.022,0.019 2.354,2.311,-0.623,-0.038,0.012,-0.056,0.019 2.537,2.024,-0.452,0.039,0.089,0.031,0.019 2.639,1.669,-0.277,-0.005,0.036,-0.008,0.019 2.707,1.314,-0.214,0.013,0.031,-0.005,0.019 2.81,0.926,-0.142,0.062,0.046,0.031,0.019
read_csv读取的数据类型为Dataframe,经过obj.dtypes能够查看每列的数据类型数组
首先说一下,我这段csv文件是没有列索引的,那么个人读取代码以下能够读取到什么呢?
import pandas as pd filename = r'Train_A/Train_A_001.csv' data = pd.read_csv(filename) print(data)
结果以下;
0.916 4.37 -1.372 0.102 0.041 0.069 0.018 0 0.892 3.955 -1.277 0.015 -0.099 -0.066 0.018 1 0.908 3.334 -1.193 0.033 -0.098 -0.059 0.018 2 1.013 3.022 -1.082 0.151 0.015 0.035 0.018 3 1.111 2.970 -1.103 -0.048 -0.175 -0.171 0.019 4 1.302 3.043 -1.089 0.011 -0.085 -0.097 0.018 5 1.552 3.017 -1.052 0.066 -0.002 -0.036 0.019 6 1.832 2.796 -0.933 0.002 -0.028 -0.075 0.019 7 2.127 2.521 -0.749 0.011 0.041 -0.022 0.019 8 2.354 2.311 -0.623 -0.038 0.012 -0.056 0.019 9 2.537 2.024 -0.452 0.039 0.089 0.031 0.019 10 2.639 1.669 -0.277 -0.005 0.036 -0.008 0.019 11 2.707 1.314 -0.214 0.013 0.031 -0.005 0.019 12 2.810 0.926 -0.142 0.062 0.046 0.031 0.019
你们能够发现,它默认你有列索引,而且把第一行的数据当作列索引,而且从第二行开始设置了行索引,因此说列索引的设置很是重要,起码在这里看来是这样的,那么如何设置呢,下面就具体分析一下。
当加上header=None的时候,代表原始文件没有列索引,这样的话会默认自动加上,除非你给定名称。结果以下:
0 1 2 3 4 5 6 0 0.916 4.370 -1.372 0.102 0.041 0.069 0.018 1 0.892 3.955 -1.277 0.015 -0.099 -0.066 0.018 2 0.908 3.334 -1.193 0.033 -0.098 -0.059 0.018 3 1.013 3.022 -1.082 0.151 0.015 0.035 0.018 4 1.111 2.970 -1.103 -0.048 -0.175 -0.171 0.019 5 1.302 3.043 -1.089 0.011 -0.085 -0.097 0.018 6 1.552 3.017 -1.052 0.066 -0.002 -0.036 0.019 7 1.832 2.796 -0.933 0.002 -0.028 -0.075 0.019 8 2.127 2.521 -0.749 0.011 0.041 -0.022 0.019 9 2.354 2.311 -0.623 -0.038 0.012 -0.056 0.019 10 2.537 2.024 -0.452 0.039 0.089 0.031 0.019 11 2.639 1.669 -0.277 -0.005 0.036 -0.008 0.019 12 2.707 1.314 -0.214 0.013 0.031 -0.005 0.019 13 2.810 0.926 -0.142 0.062 0.046 0.031 0.019
当加上header=0的时候,代表原始文件的第0行为列索引。结果以下:
0.916 4.37 -1.372 0.102 0.041 0.069 0.018 0 0.892 3.955 -1.277 0.015 -0.099 -0.066 0.018 1 0.908 3.334 -1.193 0.033 -0.098 -0.059 0.018 2 1.013 3.022 -1.082 0.151 0.015 0.035 0.018 3 1.111 2.970 -1.103 -0.048 -0.175 -0.171 0.019 4 1.302 3.043 -1.089 0.011 -0.085 -0.097 0.018 5 1.552 3.017 -1.052 0.066 -0.002 -0.036 0.019 6 1.832 2.796 -0.933 0.002 -0.028 -0.075 0.019 7 2.127 2.521 -0.749 0.011 0.041 -0.022 0.019 8 2.354 2.311 -0.623 -0.038 0.012 -0.056 0.019 9 2.537 2.024 -0.452 0.039 0.089 0.031 0.019 10 2.639 1.669 -0.277 -0.005 0.036 -0.008 0.019 11 2.707 1.314 -0.214 0.013 0.031 -0.005 0.019 12 2.810 0.926 -0.142 0.062 0.046 0.031 0.019
从这段代码咱们能够发现,少了一行,因此第一行的代码也被默认为列索引。
当没有列索引的时候,咱们也能够本身指定索引名称,方便本身记录,代码以下:
import pandas as pd filename = r'Train_A/Train_A_001.csv' data = pd.read_csv(filename,header=None,names=('a','b','c','d','e','f','g')) print(data)
经过上述代码,咱们能够指定列索引为a~f,结果以下:
a b c d e f g 0 0.916 4.370 -1.372 0.102 0.041 0.069 0.018 1 0.892 3.955 -1.277 0.015 -0.099 -0.066 0.018 2 0.908 3.334 -1.193 0.033 -0.098 -0.059 0.018 3 1.013 3.022 -1.082 0.151 0.015 0.035 0.018 4 1.111 2.970 -1.103 -0.048 -0.175 -0.171 0.019 5 1.302 3.043 -1.089 0.011 -0.085 -0.097 0.018 6 1.552 3.017 -1.052 0.066 -0.002 -0.036 0.019 7 1.832 2.796 -0.933 0.002 -0.028 -0.075 0.019 8 2.127 2.521 -0.749 0.011 0.041 -0.022 0.019 9 2.354 2.311 -0.623 -0.038 0.012 -0.056 0.019 10 2.537 2.024 -0.452 0.039 0.089 0.031 0.019 11 2.639 1.669 -0.277 -0.005 0.036 -0.008 0.019 12 2.707 1.314 -0.214 0.013 0.031 -0.005 0.019 13 2.810 0.926 -0.142 0.062 0.046 0.031 0.019
从上面的代码,咱们能够发现,没有行索引,只要设置了列索引就行,可是真的行索引不重要吗,固然不是,有些时候有些需求也是须要列索引为本身定义的名称,这里咱们一样看待,并学习一下:
当设置行索引为None的时候,也就是index_col = None,同时设置列索引的时候,代码以下:
import pandas as pd filename = r'Train_A/Train_A_001.csv' data = pd.read_csv(filename,index_col=None,header=None) print(data)
结果呢,以下:
0 1 2 3 4 5 6 0 0.916 4.370 -1.372 0.102 0.041 0.069 0.018 1 0.892 3.955 -1.277 0.015 -0.099 -0.066 0.018 2 0.908 3.334 -1.193 0.033 -0.098 -0.059 0.018 3 1.013 3.022 -1.082 0.151 0.015 0.035 0.018 4 1.111 2.970 -1.103 -0.048 -0.175 -0.171 0.019 5 1.302 3.043 -1.089 0.011 -0.085 -0.097 0.018 6 1.552 3.017 -1.052 0.066 -0.002 -0.036 0.019 7 1.832 2.796 -0.933 0.002 -0.028 -0.075 0.019 8 2.127 2.521 -0.749 0.011 0.041 -0.022 0.019 9 2.354 2.311 -0.623 -0.038 0.012 -0.056 0.019 10 2.537 2.024 -0.452 0.039 0.089 0.031 0.019 11 2.639 1.669 -0.277 -0.005 0.036 -0.008 0.019 12 2.707 1.314 -0.214 0.013 0.031 -0.005 0.019 13 2.810 0.926 -0.142 0.062 0.046 0.031 0.019
固然了,当设置行索引为0的时候,也就是index_col = 0,则第一列为索引。
固然了,在作数据分析的许多时候,咱们会读取指定的某一列,使用的函数以下:
import pandas as pd filename = r'Train_A/Train_A_001.csv' data = pd.read_csv(filename,index_col=None,header=None,usecols=[1]) print(data)
上面意思是使用第一列数据(列表默认从0开始的啊),结果以下:
1 0 4.370 1 3.955 2 3.334 3 3.022 4 2.970 5 3.043 6 3.017 7 2.796 8 2.521 9 2.311 10 2.024 11 1.669 12 1.314 13 0.926
要想一块儿读取三列,则代码以下:
import pandas as pd filename = r'Train_A/Train_A_001.csv' data = pd.read_csv(filename,index_col=None,header=None,usecols=[1,2,3]) print(data)
结果以下:
1 2 3 0 4.370 -1.372 0.102 1 3.955 -1.277 0.015 2 3.334 -1.193 0.033 3 3.022 -1.082 0.151 4 2.970 -1.103 -0.048 5 3.043 -1.089 0.011 6 3.017 -1.052 0.066 7 2.796 -0.933 0.002 8 2.521 -0.749 0.011 9 2.311 -0.623 -0.038 10 2.024 -0.452 0.039 11 1.669 -0.277 -0.005 12 1.314 -0.214 0.013 13 0.926 -0.142 0.062
使用data.head(n)返回文件的前n行内容,示例以下:
import pandas as pd filename = r'Train_A/Train_A_001.csv' data1 = pd.read_csv(filename,index_col=None,header=None) # print(data1) #读取文件的前5行 headdata = data1.head(5) print(headdata)
运行效果,返回前5行全部数据内容:
0 1 2 3 4 5 6 0 0.916 4.370 -1.372 0.102 0.041 0.069 0.018 1 0.892 3.955 -1.277 0.015 -0.099 -0.066 0.018 2 0.908 3.334 -1.193 0.033 -0.098 -0.059 0.018 3 1.013 3.022 -1.082 0.151 0.015 0.035 0.018 4 1.111 2.970 -1.103 -0.048 -0.175 -0.171 0.019
下面代码表示了函数loc返回了第一行全部列的数据,也就是说第一行的数据:
import pandas as pd filename = r'Train_A/Train_A_001.csv' data = pd.read_csv(filename,index_col=None,header=None) # print(data1) data1 = data.loc[0,:] print(data1)
由此咱们能够推断出,某几行-全部列的数据,代码以下:
import pandas as pd filename = r'Train_A/Train_A_001.csv' data = pd.read_csv(filename,index_col=None,header=None) # print(data1) # 返回第n行全部列的数据 data1 = data.loc[[1,3,5],:] print(data1)
结果展现一下:
0 1 2 3 4 5 6 1 0.892 3.955 -1.277 0.015 -0.099 -0.066 0.018 3 1.013 3.022 -1.082 0.151 0.015 0.035 0.018 5 1.302 3.043 -1.089 0.011 -0.085 -0.097 0.018
获取全部行全部列,直接看代码:
import pandas as pd filename = r'Train_A/Train_A_001.csv' data = pd.read_csv(filename,index_col=None,header=None) # print(data1) # 返回第n行全部列的数据 data1 = data.loc[:,:] print(data1)
结果就是全部行,全部列,这里就不展现了。
import pandas as pd filename = r'Train_A/Train_A_001.csv' data = pd.read_csv(filename,index_col=None,header=None) # print(data1) # 返回全部列-某行的数据 data1 = data.loc[:,0] print(data1)
运行效果以下:
0 0.916 1 0.892 2 0.908 3 1.013 4 1.111 5 1.302 6 1.552 7 1.832 8 2.127 9 2.354 10 2.537 11 2.639 12 2.707 13 2.810 Name: 0, dtype: float64
describe()统计下数据量,标准值,平均值,最大值等
data.describe()
就拿上面的csv文件为例,读取结果,解析以下:
import pandas as pd filename = r'Train_A/Train_A_001.csv' data1 = pd.read_csv(filename,index_col=None,header=None) # print(data1) print(data1.describe())
结果以下:
0 1 ... 5 6 count 14.000000 14.000000 ... 14.000000 14.000000 mean 1.764286 2.662286 ... -0.030643 0.018643 std 0.748950 0.957612 ... 0.063172 0.000497 min 0.892000 0.926000 ... -0.171000 0.018000 25% 1.037500 2.095750 ... -0.064250 0.018000 50% 1.692000 2.883000 ... -0.029000 0.019000 75% 2.491250 3.037750 ... 0.022000 0.019000 max 2.810000 4.370000 ... 0.069000 0.019000 [8 rows x 7 columns]
好比csv文件内容以下:
cut,flute_1,flute_2,flute_3 1,32.31711361,48.89261732,37.72082548 2,37.914879,49.57081504,37.72082548 3,43.08790971,50.30286727,37.72082548 4,47.8590723,51.08365203,37.84985103 5,52.25032922,51.90828793,38.17266456 6,56.28276562,52.77212655,38.61755643 7,59.97661561,53.6707451,39.17455623 8,63.3512879,54.5999392,39.83415523 9,66.4253909,55.55571585,40.58729178
那么,咱们读取到的数据,通常来讲,第一行是列标签,但是如何获取第一行的内容呢?以下:
column_headers = list(df.columns.values)
以上面的csv文件为例,读取代码以下:
import pandas as pd import numpy as np data = pd.read_csv(file1,header=0,index_col=0) # print(data) column_header = list(data.columns.values) print(column_header)
结果以下:
['flute_1', 'flute_2', 'flute_3']
这样咱们就获取告终果。
既然了解了pandas,之后也须要使用,那么我就不止想学习读取csv了,我还想学习基本的pandas数据结构,起码之后使用会知道一些,下面学习一下pandas其的基本数据结构。
~info() 获取总行数,每一个属性的类型,非空值的数量
~value_counts() 获取每一个值出现的次数。
housing["ocean_proximity"].value_counts() # 输出 <1H OCEAN 9136 INLAND 6551 NEAR OCEAN 2658 NEAR BAY 2290 ISLAND 5 Name: ocean_proximity, dtype: int64
代码以下:
from pandas.plotting import scatter_matrix attributes = ["median_house_value", "median_income", "total_rooms", "housing_median_age"] scatter_matrix(housing[attributes], figsize=(12, 8)) save_fig("scatter_matrix_plot")
sample_incomplete_rows.dropna(subset=["total_bedrooms"])
# 用中位数填充 median = housing["total_bedrooms"].median() sample_incomplete_rows["total_bedrooms"].fillna(median, inplace=True)
housing_cat = housing['ocean_proximity'] housing_cat.head(10) # 输出 # 17606 <1H OCEAN # 18632 <1H OCEAN # 14650 NEAR OCEAN # 3230 INLAND # 3555 <1H OCEAN # 19480 INLAND # 8879 <1H OCEAN # 13685 INLAND # 4937 <1H OCEAN # 4861 <1H OCEAN # Name: ocean_proximity, dtype: object housing_cat_encoded, housing_categories = housing_cat.factorize() housing_cat_encoded[:10] # 输出 # array([0, 0, 1, 2, 0, 2, 0, 2, 0, 0], dtype=int64)
pandas是基于Numpy的一个很是好用的库,正如名字同样,人见人爱,之因此以下,就在于不管是读取,处理数据,使用它都很是简单。
pandas有两种本身独有的基本数据结构,即便如此,可是它依然只是Python的一个库,因此Python中有的数据类型在这里依然使用,一样还可使用类本身定义的数据类型,只不过,pandas里面又定义了两种数据类型:Series和DataFrame。
series就如同列表同样,一系列数据,每一个数据对应于一个索引值,好比这样一个列表:[9,3,8],若是跟索引值写到一块儿,就是这样:
这种样式咱们已经熟悉了,不过有些时候,须要将其竖起来表示:
上面两种,只是表现形式上的差异罢了。
Series就是“竖起来”的列表。举个例子:
import pandas as pd s = pd.Series([1,2,3,'python']) s 0 1 1 2 2 3 3 python dtype: object
另一点也很像列表,就是里面的元素的类型,由咱们任意决定。
这里,咱们实质上建立了一个Series对象,这个对象固然就有其属性和方法了,好比下面两个属性依次能够显示Series对象的数据值和索引:
s.values array([1, 2, 3, 'python'], dtype=object) s.index RangeIndex(start=0, stop=4, step=1)
因为列表的索引只能是从0开始的整数,Series数据类型在默认状况下,其索引也是如次,不过区别于列表的是,Series能够自定义索引:
s = pd.Series(['java','python'],index=['1','2']) s 1 java 2 python dtype: object
自定义索引以后,咱们就能够根据索引操做元素,series也能够学习list操做:
s['1'] 'java'
固然了,前面定义Series对象的是,用的是列表,即 Series() 方法的参数中,第一个列表就是其数据值,若是须要定义 index,放在后面,依然是一个列表。除了这种方法以外,还能够用下面的方法定义 Series 对象:
s = {'python':800,'java':600,'c++':1000} s = pd.Series(s) s python 800 java 600 c++ 1000 dtype: int64
这样的话,索引依然能够自定义,pandas的优点就在这里体现出来,若是自定义了索引,自定的索引会自动寻找原来的索引,若是同样的话,就取代原来索引对应的值,这个能够简称为“自动对齐”,咱们举例说明:
s = pd.Series(s,index=['python','java','c','c++']) s python 800.0 java 600.0 c NaN c++ 1000.0 dtype: float64
在里面,没有c,可是索引参数中有,因而其余可以“自动对齐”的照搬原值,依然能够在新的Series对象的索引中存在,而且能够自动为其赋值NaN,若是pandas中没有值,都对齐赋值给NaN,下面来一个更特殊的:
ilist = ['a','b','c'] s = pd.Series(s,index=ilist) s a NaN b NaN c NaN dtype: float64
这样的话,新获得的Series对象索引与s对象的值一个也不对应,因此都是NaN。pandas有专门的方法来判断值是否为空。
pd.isnull(s) a True b True c True dtype: bool
也能够判断不为空:
pd.notnull(s) a False b False c False dtype: bool
固然了,也能够对索引的名字,从新定义:
s = [1,2,3,4] s = pd.Series(s,index=['python','java','c','c++']) s python 1 java 2 c 3 c++ 4 dtype: int64 s.index = ['a','b','c','d'] s a 1 b 2 c 3 d 4 dtype: int64
DataFrame是一个表格型的数据结构,它含有一组有序的列,每类能够是不一样的值类型(数值,字符串,布尔值)。DataFrame既有行索引也有列索引,它能够被看作由Series组成的字典(共同使用同一个索引)。跟其余相似的数据结构相比(如R的data.frame)DataFrame中面向行和面向列的操做基本上是平衡的,其实DataFrame中的数据是以一个或者多个二维块存放的(而不是列表,字典或者其余一维数据结构)。
DataFrame 是一种二维的数据结构,很是接近于电子表格或者相似 mysql 数据库的形式。它的竖行称之为 columns,横行跟前面的 Series 同样,称之为 index,也就是说能够经过 columns 和 index 来肯定一个主句的位置。(有人把 DataFrame 翻译为“数据框”,是否是还能够称之为“筐”呢?向里面装数据嘛。)
首先给一个例子:
>>> import pandas as pd >>> from pandas import Series, DataFrame >>> data = {"name":["yahoo","google","facebook"], "marks": [200,400,800], "price":[9, 3, 7]} >>> f1 = DataFrame(data) >>> f1 marks name price 0 200 yahoo 9 1 400 google 3 2 800 facebook 7
这是定义一个 DataFrame 对象的经常使用方法——使用 dict 定义。字典的“键”("name","marks","price")就是 DataFrame 的 columns 的值(名称),字典中每一个“键”的“值”是一个列表,它们就是那一竖列中的具体填充数据。上面的定义中没有肯定索引,因此,按照惯例(Series 中已经造成的惯例)就是从 0 开始的整数。从上面的结果中很明显表示出来,这就是一个二维的数据结构(相似 excel 或者 mysql 中的查看效果)。
上面的数据显示中,columns 的顺序没有规定,就如同字典中键的顺序同样,可是在 DataFrame 中,columns 跟字典键相比,有一个明显不一样,就是其顺序能够被规定,向下面这样作:
>>> f2 = DataFrame(data, columns=['name','price','marks']) >>> f2 name price marks 0 yahoo 9 200 1 google 3 400 2 facebook 7 800
跟Series相似的,DataFrame数据的索引也能够自定义:
>>> f3 = DataFrame(data, columns=['name', 'price', 'marks', 'debt'], index=['a','b','c']) >>> f3 name price marks debt a yahoo 9 200 NaN b google 3 400 NaN c facebook 7 800 NaN
你们还要注意观察上面的显示结果。由于在定义 f3 的时候,columns 的参数中,比以往多了一项('debt'),可是这项在 data 这个字典中并无,因此 debt 这一竖列的值都是空的,在 Pandas 中,空就用 NaN 来表明了。
定义 DataFrame 的方法,除了上面的以外,还可使用“字典套字典”的方式。
>>> newdata = {"lang":{"firstline":"python","secondline":"java"}, "price":{"firstline":8000}} >>> f4 = DataFrame(newdata) >>> f4 lang price firstline python 8000 secondline java NaN
在字典中就规定好数列名称(第一层键)和每横行索引(第二层字典键)以及对应的数据(第二层字典值),也就是在字典中规定好了每一个数据格子中的数据,没有规定的都是空。
>>> DataFrame(newdata, index=["firstline","secondline","thirdline"]) lang price firstline python 8000 secondline java NaN thirdline NaN NaN
若是额外肯定了索引,就如同上面显示同样,除非在字典中有相应的索引内容,不然都是 NaN。
前面定义了 DataFrame 数据(能够经过两种方法),它也是一种对象类型,好比变量 f3 引用了一个对象,它的类型是 DataFrame。承接之前的思惟方法:对象有属性和方法。
>>> f3.columns Index(['name', 'price', 'marks', 'debt'], dtype=object)
DataFrame 对象的 columns 属性,可以显示素有的 columns 名称。而且,还能用下面相似字典的方式,获得某竖列的所有内容(固然包含索引):
>>> f3['name'] a yahoo b google c facebook Name: name
这是什么?这其实就是一个 Series,或者说,能够将 DataFrame 理解为是有一个一个的 Series 组成的。
一直耿耿于怀没有数值的那一列,下面的操做是统一给那一列赋值:
>>> f3['debt'] = 89.2 >>> f3 name price marks debt a yahoo 9 200 89.2 b google 3 400 89.2 c facebook 7 800 89.2
除了可以统一赋值以外,还可以“点对点”添加数值,结合前面的 Series,既然 DataFrame 对象的每竖列都是一个 Series 对象,那么能够先定义一个 Series 对象,而后把它放到 DataFrame 对象中。以下:
>>> sdebt = Series([2.2, 3.3], index=["a","c"]) #注意索引 >>> f3['debt'] = sdebt
将 Series 对象(sdebt 变量所引用) 赋给 f3['debt']列,Pandas 的一个重要特性——自动对齐——在这里起作用了,在 Series 中,只有两个索引("a","c"),它们将和 DataFrame 中的索引自动对齐。因而乎:
>>> f3 name price marks debt a yahoo 9 200 2.2 b google 3 400 NaN c facebook 7 800 3.3
自动对齐以后,没有被复制的依然保持 NaN。
还能够更精准的修改数据吗?固然能够,彻底仿照字典的操做:
>>> f3["price"]["c"]= 300 >>> f3 name price marks debt a yahoo 9 200 2.2 b google 3 400 NaN c facebook 300 800 3.3
DataFrame.values 返回DataFrame的Numpy表示形式
仅返回DataFrame中的值,将删除轴标签
全部列都是相同类型(例如:int64)的DataFrame会生成相同类型的数组。
>>> df = pd.DataFrame({'age': [ 3, 29], ... 'height': [94, 170], ... 'weight': [31, 115]}) >>> df age height weight 0 3 94 31 1 29 170 115 >>> df.dtypes age int64 height int64 weight int64 dtype: object >>> df.values array([[ 3, 94, 31], [ 29, 170, 115]], dtype=int64)
具备混合类型列的DataFrame(例如,str / object,int64,float32)致使最宽泛类型的ndarray,其适应这些混合类型(例如,对象)。
>>> df2 = pd.DataFrame([('parrot', 24.0, 'second'), ... ('lion', 80.5, 1), ... ('monkey', np.nan, None)], ... columns=('name', 'max_speed', 'rank')) >>> df2.dtypes name object max_speed float64 rank object dtype: object >>> df2.values array([['parrot', 24.0, 'second'], ['lion', 80.5, 1], ['monkey', nan, None]], dtype=object)
这节主要学习如何对pandas的DataFrame进行切片,包括取某行,某列,某几行,某几列以及多重索引的取数方法。
测试的CSV文件以下(test.csv):
注意:测试数据没有行标题和列标题
2.95072,3.37973,3.03758,0.711681,3.37973,3.37973 2.95072,3.37973,3.03758,0.711681,3.37973,3.37973 3.19946,3.72793,3.22612,0.899132,3.72793,3.72793 3.23699,3.72295,3.29885,0.988473,3.72295,3.72295 3.23179,3.71829,3.29314,0.96549,3.71829,3.71829 3.29573,3.76237,3.32046,0.978557,3.76237,3.76237 3.32537,3.82346,3.35758,1.04363,3.82346,3.82346 3.34407,3.87181,3.38804,1.05891,3.87181,3.87181 3.4196,3.88913,3.44196,1.12763,3.88913,3.88913 3.3904,3.87997,3.42206,1.10885,3.87997,3.87997
首先说明一下,直接read_csv和转换为DataFrame的效果,
import pandas as pd filecontent = pd.read_csv('test.csv',header=None,names=['a','b','c','d','e','f']) print(type(filecontent)) df = pd.DataFrame(filecontent) print(type(df))
先看结果:
<class 'pandas.core.frame.DataFrame'> <class 'pandas.core.frame.DataFrame'>
从结果来看,因此说两个效果是同样的,转不转换都同样。
直接拿第四列的数据(列表默认从0开始取),代码以下:
import pandas as pd filecontent = pd.read_csv('test.csv',header=None) df = pd.DataFrame(filecontent,index=None) index4 = df.iloc[:,3] print(index4)
结果:
0 0.711681 1 0.711681 2 0.899132 3 0.988473 4 0.965490 5 0.978557 6 1.043630 7 1.058910 8 1.127630 9 1.108850 Name: 3, dtype: float64
当加上索引,就取索引,两个效果是同样的,代码以下:
import pandas as pd filecontent = pd.read_csv('test.csv',header=None,names=['a','b','c','d','e','f']) print(filecontent.a) print(filecontent['a'])
结果:
0 2.95072 1 2.95072 2 3.19946 3 3.23699 4 3.23179 5 3.29573 6 3.32537 7 3.34407 8 3.41960 9 3.39040 Name: a, dtype: float64 0 2.95072 1 2.95072 2 3.19946 3 3.23699 4 3.23179 5 3.29573 6 3.32537 7 3.34407 8 3.41960 9 3.39040 Name: a, dtype: float64
使用索引和不适用索引取多列的方法
import pandas as pd filecontent = pd.read_csv('test.csv',header=None,names=['a','b','c','d','e','f']) df = pd.DataFrame(filecontent) # 取某几列的方法一使用索引 result = df[['b','c']] print(result) # 取某几列的方法一不使用索引取前两列 result1 = df.iloc[:,:2] print(result1)
结果:
b c 0 3.37973 3.03758 1 3.37973 3.03758 2 3.72793 3.22612 3 3.72295 3.29885 4 3.71829 3.29314 5 3.76237 3.32046 6 3.82346 3.35758 7 3.87181 3.38804 8 3.88913 3.44196 9 3.87997 3.42206 a b 0 2.95072 3.37973 1 2.95072 3.37973 2 3.19946 3.72793 3 3.23699 3.72295 4 3.23179 3.71829 5 3.29573 3.76237 6 3.32537 3.82346 7 3.34407 3.87181 8 3.41960 3.88913 9 3.39040 3.87997
代码以下;
import pandas as pd filecontent = pd.read_csv('test.csv',header=None,names=['a','b','c','d','e','f']) df = pd.DataFrame(filecontent) # 取某几行的方法一使用索引 result = df[1:2] print(result) print('************************************************') # 取某几列的方法一不使用索引取第一行 result1 = df.ix[1] print(result1) print('************************************************') # 取某几列的方法一不使用索引取第一行 result2 = df.iloc[1,:] print(result2)
结果以下:
a b c d e f 1 2.95072 3.37973 3.03758 0.711681 3.37973 3.37973 ************************************************ a 2.950720 b 3.379730 c 3.037580 d 0.711681 e 3.379730 f 3.379730 Name: 1, dtype: float64 ************************************************ a 2.950720 b 3.379730 c 3.037580 d 0.711681 e 3.379730 f 3.379730 Name: 1, dtype: float64
代码以下:
import pandas as pd filecontent = pd.read_csv('test.csv',header=None,names=['a','b','c','d','e','f'],index_col=None) df = pd.DataFrame(filecontent) # 取某几行的方法一不使用索引取前两行 result1 = df.iloc[:2,] print(result1)
结果以下:
a b c d e f 0 2.95072 3.37973 3.03758 0.711681 3.37973 3.37973 1 2.95072 3.37973 3.03758 0.711681 3.37973 3.37973
代码以下:
import pandas as pd filecontent = pd.read_csv('test.csv',header=None,names=['a','b','c','d','e','f'],index_col=None) df = pd.DataFrame(filecontent) # 取DataFrame的某特定位置元素的方法 result = df.ix[1,2] print(result)
结果以下:
3.0375799999999997
代码以下:
import pandas as pd filecontent = pd.read_csv('test.csv',header=None,names=['a','b','c','d','e','f'],index_col=None) df = pd.DataFrame(filecontent) # 取DataFrame的多行多列的方法 # 取前两行,前三列 result = df.ix[:2,:3] print(result) # 取前两行,前三列 result1 = df.iloc[:2,:3] print(result1)
结果以下:
a b c 0 2.95072 3.37973 3.03758 1 2.95072 3.37973 3.03758 2 3.19946 3.72793 3.22612 a b c 0 2.95072 3.37973 3.03758 1 2.95072 3.37973 3.03758
删除Series的元素或者DataFrame的某一行(列)的意思,经过对象的方法,删除Series的一个元素。
其方法调用以下:
def drop(self, labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise'):
对象的 .drop(labels, axis=0) 方法返回的是一个新对象,元对象不会被改变。
In[11]: ser = Series([4.5,7.2,-5.3,3.6], index=['d','b','a','c']) In[13]: ser.drop('c') Out[13]: d 4.5 b 7.2 a -5.3 dtype: float64
drop函数默认删除行,列须要加axis = 1
In[17]: df = DataFrame(np.arange(9).reshape(3,3), index=['a','c','d'], columns=['oh','te','ca']) In[18]: df Out[18]: oh te ca a 0 1 2 c 3 4 5 d 6 7 8 In[19]: df.drop('a') Out[19]: oh te ca c 3 4 5 d 6 7 8 In[20]: df.drop(['oh','te'],axis=1) Out[20]: ca a 2 c 5 d 8
采用drop方法,有下面三种等价的表达式
1. DF= DF.drop('column_name', axis=1); 2. DF.drop('column_name',axis=1, inplace=True) 3. DF.drop([DF.columns[[0,1, 3]]], axis=1, inplace=True) # Note: zero indexed
注意:凡是会对原数组作出修改并返回一个新数组的,每每都会有一个inplace可选参数。若是手动设定位True(默认为False),那么原数组就直接被替换。也就是说,采用inplace = True以后,原数组名如(状况2 和3 所示)对应的内存值直接改变。
而采用inplace =False 以后,原数组名对应的内存值并不改变,须要将新的结果赋给一个新的数组或者覆盖原数组的内存位置。
df['Name'] = df['Name'].astype(np.datetime64)
DataFrame.astype() 方法可对整个DataFrame或某一列进行数据格式转换,支持Python和NumPy的数据类型。
注意:要合并的两个文件行数须要相同,若不一样可指定数组下标使其相同
代码以下:
# _*_ coding:utf-8 _*_ import csv aFile = open('a.csv', 'r') aInfo = csv.reader(aFile) bfile = open('b.csv', 'r') bInfo = csv.reader(bfile) cfile = open('c.csv', 'w') abcsv = csv.writer(cfile, dialect='excel') a=[] a=list() b=[] b=list() for info in aInfo: a.append(info) for info in bInfo: b.append(info ) for index in range(len(b)): a[index+1].extend(b[index]) abcsv.writerow(a[index+1])
当作数据分析与挖掘的时候,常常遇到要合并CSV文件的问题,因此此处记录一下使用python中的Pandas库进行拼接。
import pandas as pd import os orgin_dir = "Train_A" result_dir = "result_A" for filename in os.listdir(orgin_dir): print(filename) # header=None表示原始文件数据没有列索引,这样的话read_csv会自动加上列索引 a = pd.read_csv('Train_A/'+filename,header=None) # header=0表示不保留列名,index=False表示不保留行索引,mode='a'表示附加方式写入,文件原有内容不会被清除 a.to_csv('all.csv',mode='a',index=False,header=False)
import pandas as pd import os orgin_dir = "Train_A" result_dir = "result_A" for filename in os.listdir(orgin_dir): print(filename) # header=None表示原始文件数据没有列索引,这样的话read_csv会自动加上列索引 pd.read_csv('Train_A/'+filename,header=None) # header=0表示不保留列名,index=False表示不保留行索引,mode='a'表示附加方式写入,文件原有内容不会被清除 pd.to_csv('all.csv',mode='a',index=False,header=False)
排序是按照某一列的大小进行排序,Python3.x目前提供两个函数
这个函数彷佛不建议使用了,推荐使用sort_values,详情参考:官方文档
## 参数 sort_index(axis=0, level=None, ascending=True, inplace=False, kind='quicksort', na_position='last', sort_remaining=True, by=None) #### 参数说明 axis:0按照行名排序;1按照列名排序 level:默认None,不然按照给定的level顺序排列---貌似并非,文档 ascending:默认True升序排列;False降序排列 inplace:默认False,不然排序以后的数据直接替换原来的数据框 kind:默认quicksort,排序的方法 na_position:缺失值默认排在最后{"first","last"} by:按照那一列数据进行排序,可是by参数貌似不建议使用
举例:
## 对x1列升序排列,x2列升序。处理x1有相同值的状况 import pandas as pd x = pd.DataFrame({"x1":[1,2,2,3],"x2":[4,3,2,1]}) x.sort_index(by = ["x1","x2"],ascending = [False,True])
## 参数 DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last') #### 参数说明 axis:{0 or ‘index’, 1 or ‘columns’}, default 0,默认按照索引排序,即纵向排序,若是为1,则是横向排序 by:str or list of str;若是axis=0,那么by="列名";若是axis=1,那么by="行名"; ascending:布尔型,True则升序,能够是[True,False],即第一字段升序,第二个降序 inplace:布尔型,是否用排序后的数据框替换现有的数据框 kind:排序方法,{‘quicksort’, ‘mergesort’, ‘heapsort’}, default ‘quicksort’。彷佛不用太关心 na_position : {‘first’, ‘last’}, default ‘last’,默认缺失值排在最后面
## 沿着轴方向按指定值排序 x.sort_values(by="x1",ascending= False)
## 沿着行方向按指定行排序 x.sort_values(by = 1,ascending=False,axis=1)
此外,在学习的时候,我参考了别人的知乎内容,并查看官网,而后汇总了pandas官网中比较经常使用的函数和方法,以方便本身记忆。其实这个比较全面的归纳了pandas的全部知识点,只不过没有举例子,可是要是认真看了我上面的两个大的例子,学习下面的知识点,根本不费吹灰之力。
首先,咱们使用以下的缩写:
df:任意的Pandas DataFrame对象 s:任意的Pandas Series对象
同时导入pandas包和numpy包
import pandas as pd import numpy as np
当看到np和pd的时候,咱们就知道其是什么含义(这些缩写都是你们默认的)。
原文:
pd.read_csv(filename) | From a CSV file pd.read_table(filename) | From a delimited text file (like TSV) pd.read_excel(filename) | From an Excel file pd.read_sql(query, connection_object) | Read from a SQL table/database pd.read_json(json_string) | Read from a JSON formatted string, URL or file. pd.read_html(url) | Parses an html URL, string or file and extracts tables to a list of dataframes pd.read_clipboard() | Takes the contents of your clipboard and passes it to read_table() pd.DataFrame(dict) | From a dict, keys for columns names, values for data as lists
原文:
df.to_csv(filename) | Write to a CSV file df.to_excel(filename) | Write to an Excel file df.to_sql(table_name, connection_object) | Write to a SQL table df.to_json(filename) | Write to a file in JSON format
原文:
pd.DataFrame(np.random.rand(20,5)) | 5 columns and 20 rows of random floats pd.Series(my_list) | Create a series from an iterable my_list df.index = pd.date_range('1900/1/30', periods=df.shape[0]) | Add a date index
原文:
df.head(n) | First n rows of the DataFrame df.tail(n) | Last n rows of the DataFrame df.shape | Number of rows and columns df.info() | Index, Datatype and Memory information df.describe() | Summary statistics for numerical columns s.value_counts(dropna=False) | View unique values and counts df.apply(pd.Series.value_counts) | Unique values and counts for all columns
原文:
df[col] | Returns column with label col as Series df[[col1, col2]] | Returns columns as a new DataFrame s.iloc[0] | Selection by position s.loc['index_one'] | Selection by index df.iloc[0,:] | First row df.iloc[0,0] | First element of first column
原文:
df.columns = ['a','b','c'] | Rename columns pd.isnull() | Checks for null Values, Returns Boolean Arrray pd.notnull() | Opposite of pd.isnull() df.dropna() | Drop all rows that contain null values df.dropna(axis=1) | Drop all columns that contain null values df.dropna(axis=1,thresh=n) | Drop all rows have have less than n non null values df.fillna(x) | Replace all null values with x s.fillna(s.mean()) | Replace all null values with the mean (mean can be replaced with almost any function from the statistics section) s.astype(float) | Convert the datatype of the series to float s.replace(1,'one') | Replace all values equal to 1 with 'one' s.replace([1,3],['one','three']) | Replace all 1 with 'one' and 3 with 'three' df.rename(columns=lambda x: x + 1) | Mass renaming of columns df.rename(columns={'old_name': 'new_ name'}) | Selective renaming df.set_index('column_one') | Change the index df.rename(index=lambda x: x + 1) | Mass renaming of index
原文:
df[df[col] > 0.5] | Rows where the column col is greater than 0.5 df[(df[col] > 0.5) & (df[col] < 0.7)] | Rows where 0.7 > col > 0.5 df.sort_values(col1) | Sort values by col1 in ascending order df.sort_values(col2,ascending=False) | Sort values by col2 in descending order df.sort_values([col1,col2],ascending=[True,False]) | Sort values by col1 in ascending order then col2 in descending order df.groupby(col) | Returns a groupby object for values from one column df.groupby([col1,col2]) | Returns groupby object for values from multiple columns df.groupby(col1)[col2] | Returns the mean of the values in col2, grouped by the values in col1 (mean can be replaced with almost any function from the statistics section) df.pivot_table(index=col1,values=[col2,col3],aggfunc=mean) | Create a pivot table that groups by col1 and calculates the mean of col2 and col3 df.groupby(col1).agg(np.mean) | Find the average across all columns for every unique col1 group df.apply(np.mean) | Apply the function np.mean() across each column nf.apply(np.max,axis=1) | Apply the function np.max() across each row
原文:
df1.append(df2) | Add the rows in df1 to the end of df2 (columns should be identical) pd.concat([df1, df2],axis=1) | Add the columns in df1 to the end of df2 (rows should be identical) df1.join(df2,on=col1,how='inner') | SQL-style join the columns in df1 with the columns on df2 where the rows for col have identical values. how can be one of 'left', 'right', 'outer', 'inner'
原文:
df.describe() | Summary statistics for numerical columns df.mean() | Returns the mean of all columns df.corr() | Returns the correlation between columns in a DataFrame df.count() | Returns the number of non-null values in each DataFrame column df.max() | Returns the highest value in each column df.min() | Returns the lowest value in each column df.median() | Returns the median of each column df.std() | Returns the standard deviation of each column
参考http://wiki.jikexueyuan.com/project/start-learning-python/311.html
https://zhuanlan.zhihu.com/p/25630700
https://www.dataquest.io/blog/pandas-cheat-sheet/