数据科学家 课程笔记

pandas 全称 Python for Data Analysis,作用为让用可以快速操作及分析资料:

import pandas
df = pandas.read_csv('Data/example.csv')    #pandas.read包含很多种格式包括csv, json等
print(df)

df = pandas.read_excel('Data/GDP.xls')
df

   4/5/2014 13:34 Apples 73
0 4/5/2014 3:41 Cherries 85
1 4/6/2014 12:46 Pears 14
2 4/8/2014 8:59 Oranges 52
3 4/10/2014 2:07 Apples 152
4 4/10/2014 18:10 Bananas 23
5 4/10/2014 2:40 Strawberries 98

这里显示的不是很好,如果在jupyter notebook会显示表格的html

数据整理,DataFrame意思为简易的数据格式,将数据进行结构化整理,让用户可以快速操作及分析数据资料,例如转换成CSV, excel等文件格式

import pandas
newsdf = pandas.DataFrame(newsary) # newsary=['title': 'info', 'url'='info']字典包含在列表内,转换成pandas.DataFrame
newsdf.to_excel('news.xlsx')  # 再将数据转到excel文件

pandas使用

import pandas 
df = pandas.DataFrame([['Frank', 'M', 29], ['Mary', 'F', 23], ['Tom', 'M', 35], ['Ted', 'M', 30]])

      0    1     2

  0  Frank  M    29
  1  Mary   F    23
  2  Tom   M    35
  3  Ted   M    30

df.columns

RangeIndex(start=0, stop=3, step=1)  栏位名称

df.columns = ['name', 'gender', 'age']   # 加入栏目

    name  gender  age

0   Frank  M       29
1   Mary   F      23
3   Tom   M      35

df.info()  # 限时data frame 内容
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 3 columns):
name      4 non-null object
gender    4 non-null object
age       4 non-null int64
dtypes: int64(1), object(2)
memory usage: 176.0+ bytes

-------------------------------------------------------------------
df.ix[1]    # 存取元素与切割(indexing & Slicing), [1]代表将第一列的内容显示出来

df.ix[1:4]    # 将1到4列的内容显示出来
name      Mary
gender       F
age         23
Name: 1, dtype: object

    name  gender  age
  1  Mary   F    23
  2  Tom   M    35
  3  Ted   M    30

df['name']    # 将name栏位的内容全部取出来

df[['name', 'age']]    # 使用两个中括号将name 和 age栏位的内容都取出来
df.ix[1:2, ['name', 'age']] #将 1到2列 name age的内容取出来,注意中括号使用的格式


  name  age  

1  Mary  23

2  Tom  35

df['gender']=='M'   # 通过设置栏位的判断,返回bool的值,即True or False

df[df['gender']==M]    # 这样可以将男性的值全部显示出来
df[(df['gender']=='M')&(df['age']>=30)]    # 使用and的方式显示
df[(df['gender']=='M')|(df['age']>=30)]     # 使用or的方式显示

新增栏位:

df['employee']=True        # 增加栏位


del df['employee']
# OR
df = df.drop('employee', 1)

新增列位:

df.loc[4]={'age':20,'gender':'F','name':'Qoo','employee':False}    # 指定列增加内容,注意使用中括号

df.append(pandas.DataFrame([{'age':20, 'gender':'F','name':'Lili','employee':True}]),ignore_index=True)    # 增加另外一列内容,可以一次增加多列,将字典加入list里面,不指定列的序列号,要注意格式

df.drop(6)    # 删除第6列

 增加索引:

df['userid'] = range(101, 109)    #首先增加栏位 

df.set_index('userid', inplace=True)    #再设置index索引

根据引索取值:

df.iloc[1]        # 取第一行的值

df.iloc[[1,3,5]]    # 取第一,第三,第五行的值,将值包装在list里面取值,所以是两个中括号


df.ix[[101, 103, 105]]    # 根据引索取值

df.loc[[101, 103, 105]]    # 根据引索取值

================================================================

Numpy

import numpy
a = numpy.array([1, 2, 3])
b = numpy.array([2, 3, 4])
a * b

array([2, 6, 12]) 得出的结果

原文地址:https://www.cnblogs.com/ecwork/p/7787378.html