numpy

NumPy对于轴的编号由外向内,从行到列

In [4]: a.reshape(2,5,2)
Out[4]:
array([[[ 0, 1],
[ 2, 3],
[ 4, 5],
[ 6, 7],
[ 8, 9]],

[[10, 11],
[12, 13],
[14, 15],
[16, 17],
[18, 19]]])
In [6]: a.reshape(1,2,5,2)
Out[6]:
array([[[[ 0, 1],
[ 2, 3],
[ 4, 5],
[ 6, 7],
[ 8, 9]],

[[10, 11],
[12, 13],
[14, 15],
[16, 17],
[18, 19]]]])

广播的条件:维度数相同(如都是三维),某array的一个或多个维度的长度是1/维度数不同,添加长度为1的维度
7f28d01b1f6ea480369acb422561f8e4.png
更高维的数据:可以采取降维,
348af567b7c1dc5dc36315c1b0a38bf5.png

  • 创建数据
    np.array创建数组
    array.ndim返回数组维度
  • 添加数据
    cars = np.concatenate([cars1, cars2])
test1 = np.array([5, 10, 12, 6])
test2 = np.array([5.1, 8.2, 11, 6.3])

# 首先需要把它们都变成二维,下面这两种方法都可以加维度
test1 = np.expand_dims(test1, 0)
test2 = test2[np.newaxis, :]

print("test1加维度后 ", test1)
print("test2加维度后 ", test2)

# 然后再在第一个维度上叠加
all_tests = np.concatenate([test1, test2])
print("括展后\n", all_tests)
  • 合并数据
a = np.array([
[1,2,3],
[4,5,6]
])
b = np.array([
[7,8],
[9,10]
])

print(np.concatenate([a,b], axis=1)) # 这个没问题
# print(np.concatenate([a,b], axis=0)) # 这个会报错
'''
输出:
[[ 1 2 3 7 8]
[ 4 5 6 9 10]]
'''
    • 还有np.vstacknp.hstack水平合并,竖直合并
  • .size获取大小,.shape获取形状元组
  • 条件筛选
    • print(a[a>7]),逻辑:先得到a每个元素的布尔数组,再打印
    • np.where(condition,a,b),把所有符合条件的换成a,不符合的换成b
  • 基础运算:
    • ±*/在numpy数组中都是逐元素批量运算
    • 数据统计分析:
      • np.max(a) or a.max()都可以
      • a.prod累乘,a.sum()求和,mean,std(标准差),median(中位数)
    • 特殊运算符:
      • np.argmax or np.argmin返回最值对应的下标
      • np.ceil or np.flour向上/下取整
      • np.clip上下界限截取(控制在上下界之间)
  • 改变数据形态
    • 0b2b3834ee67596340853c99de670edd.png
    • 一般来说,在数据分析统计,机器学习中的数据,都是以二维来存储的。行是数据样本(第一维度),列是特征(第二维度)。
    • 拆解:
a = np.array(
[[ 1, 11, 2, 22],
[ 3, 33, 4, 44],
[ 5, 55, 6, 66],
[ 7, 77, 8, 88]]
)
print(np.split(a, indices_or_sections=2, axis=0)) # 分成两段
print(np.split(a, indices_or_sections=[2,3], axis=1)) # 在第二维度,分片成 [:2],[2:3],[3:]

读取保存数据

读取

  • np.loadtxt("read-save-data/data.csv", delimiter=",", skiprows=1, dtype=np.int64)
    skiprows:跳过第一行 delimiter:分割符
  • np.fromstring(row_string, dtype=np.int64, sep=",")
    只能读取一个数值序列

保存

  • 保存为通用数据格式
    np.savetxt("read-save-data/save_data.csv", data, delimiter=",", fmt='%s')
  • np特有的二进制格式
    np.save("read-save-data/save_data.npy", data)
    文件拓展名为npy,可以直接用np.load来读取
  • 一个文件中保存多个array
    np.savez("read-save-data/save_data.npz", train=train_data, test=test_data)
    后面的train,test是自定义的参数,可以在读取该文件时作为索引
    np.savez_compressed()压缩更节省空间

标准数据生成

np.full([shape],num),生成shape形状,值为num的array
np.linspace(start,end,num)从start到end中间共num个间隔相等的数据

随机数和随机操作

np.random.rand((shape))
np.random.random([shape])均用于生成[0,1]之间的数
np.random.randn((shape))生成正态分布
np.random.randint(low,high,size)

#对已有数据的随机化处理
data = np.array([2,1,3,4,6])
print("选一个:", np.random.choice(data))
print("选多个:", np.random.choice(data, size=3))
print("不重复地选多个(不放回):", np.random.choice(data, size=3, replace=False))
print("带权重地选择:", np.random.choice(data, size=10, p=[0,0,0,0.2,0.8]))

np.random.shuffle()用于数据重新洗牌:注意可能用到源数据的时候进行备份
np.random.permutation可以直接生成乱序的序列号,或者处理多维数据
np.random.normal(mean,方差,形状)正态分布
np.random.uniform(low ,high ,size)均匀分布

  • 随机数种子(当需要两次一模一样的随机初始化时)
    (同一个数字产生的随机数相同)
np.random.seed(1)
#此后的生成随机数相同

pandas

1.creating,reading and writing

creating data

import pandas as pd:常用
DataFrame:一种表格
125967bfb287e8036d8d4ee2f687a69f.png
(字典的键是栏目名,而字典的值是entries/条目)

  • 可以看到字典的键变成了列标,使用参数指定行标(row)
    9f224e12e52068ba832377d21e13dbea.png
    Series:一种列表(本质上是DataFrame的单独一列)
  • 使用参数指定行标和总的名字
    e30e7cbc31d62a4bba63295249af3bdf.png

reading data files

csv:So a CSV file is a table of values separated by commas. Hence the name: “Comma-Separated Values”, or CSV.

wine = pd.read_csv("......csv",index_col =0 )
wine.head()
#当有内置索引的时候pandas不会默认启用,使用指定参数就行

ps:注意字典创建的值要用[]!!!
保存为csv:DataFrame.to_csv(‘name of the file’)

2.Indexing, Selecting & Assigning

  • 访问某column:reviews.country/reviews['country']都可以(后者可以用于撞词(这一栏就叫column))

index-based selection(iloc)

  • Both loc and iloc are row-first, column-second. This is the opposite of what we do in native Python, which is column-first, row-second.
    所以reviews.iloc[0]取第一行reviews.iloc[:,0]取第一列
    如果索引是负数:从末尾开始数

label-based selection(loc)

reviews.loc[:, ['taster_name', 'taster_twitter_handle', 'points']]
(最前面也可以是数字)

choosing

iloc uses the Python stdlib indexing scheme, where the first element of the range is included and the last one excluded. So 0:10 will select entries 0,…,9. loc, meanwhile, indexes inclusively. So 0:10 will select entries 0,…,10.

Manipulating the index(操作索引)

reviews.set_index("title")加一行的列名为title

conditional selection

reviews.loc[reviews.country == 'Italy' & reviews.point >= 90]
返回其country词条为意大利,得分90以上的词条
reviews.loc[reviews.coutry.isin(['Italy','France'])]判断是否在里面
reviews.loc[reviews.price.notnull()]返回不是空缺的地方(也有isnull())
ps:
1.sample_reviews = reviews.iloc[[1,2,3,5,8]]注意取多项的时候整体作为一个列表传入
2.df = reviews.loc[[0,1,10,100],['country','province','region_1','region_2']],传入两个列表,逗号隔开
3.top_oceania_wines = reviews[(reviews.points >=95) & ((reviews.country == 'Australia')|(reviews.country == 'New Zealand'))]比较运算符,永远括起来才不会出错!!!

3.Summary functions and maps

summary function

#对数字
s = pd.Series([1, 2, 3])
s.describe()
'''
output:
count 3.0
mean 2.0
std 1.0
min 1.0
25% 1.5
50% 2.0
75% 2.5
max 3.0
dtype: float64
'''
#对字符
s = pd.Series(['a', 'a', 'b', 'c'])
s.describe()
'''
count 4
unique 3
top a
freq 2
dtype: object
'''

reviews.points.unique(),有多少个
reviews.points.value_counts频数统计图

maps(映射)

#第一种map方式
review_mean_points = reviews.points.mean()
reviews.points.map(lambda p:p-review_mean_points)
#返回的points一栏被正则化至平均值为0

#第二种map方式
def regulation(row):
row.points = row.points - review_mean_points
return row
reviews.apply(regulation,axis = 'column')

内置:
reviews.points+'-'+reviews.countrys用-符号将两组Series连接起来
ps:
pandas.DataFrame.idxmax()返回指定轴上最大值出现的第一个索引

n_trop = reviews.description.map(lambda desc: "tropical" in desc).sum()
n_fruity = reviews.description.map(lambda desc: "fruity" in desc).sum()
descriptor_counts = pd.Series([n_trop, n_fruity], index=['tropical', 'fruity'])
#统计出现关键词的描述的数量
n_trop = reviews.description.str.count("tropical").sum()
n_fruity = reviews.description.str.count("fruity").sum()
descriptor_counts = pd.Series([n_trop, n_fruity], index=['tropical', 'fruity'])
#统计关键词的频数


def stars(row):
if row.country == 'Canada':
return 3
elif row.points >= 95:
return 3
elif row.points >= 85:
return 2
else:
return 1

star_ratings = reviews.apply(stars, axis='columns')
#返回的是一个由stars函数的返回值构成的Series

##也可以这么写(loc是为了索引对齐)
# 初始化一个与 reviews 索引一致的 Series,默认值为 0
star_ratings = pd.Series(0, index=reviews.index)

# 定义逻辑
three_star = reviews[(reviews.points >= 95) | (reviews.country == 'Canada')]
two_star = reviews[(reviews.points >= 85) & (reviews.points < 95) & (reviews.country != 'Canada')]
one_star = reviews[(reviews.points < 85) & (reviews.country != 'Canada')]

# 分配星级
star_ratings.loc[three_star.index] = 3
star_ratings.loc[two_star.index] = 2
star_ratings.loc[one_star.index] = 1

4.grouping and sorting

groupwise analysis

  • groupby():You can think of each group we generate as being a slice of our DataFrame containing only data with values that match. This DataFrame is accessible to us directly using the apply() method, and we can then manipulate the data in any way we see fit.
  • 以下两行等效
    reviews.groupby('points').points.count()
    reviews.points.value_counts()
    e.g:返回不同国家和省份之间最好的酒
    reviews.groupby(['country', 'province']).apply(lambda df: df.loc[df.points.idxmax()])
  • groupby()的一个method:agg(),可以同时使用多个方法``agg([len,max,min])`

multi_indexes

e.g:
4c0a7ce62e6a499ff39582a8d6be2ce0.png
reset_index()重置回常规的index

sorting

groupby()的输出的顺序是基于index的大小,使用countries_reviewed.sort_values(by='len')可以解决(默认升序,可以用ascending=False参数来调整)
也有sort_index(),可以对by传入一个参数列表,同时使用多个排序依据

sorted_df = df.sort_values(by=['A', 'B'], ascending=[True, False])
两列
country_variety_counts = reviews.groupby(['country','variety']).size().sort_values(ascending = False)
什么组合最常见!

5.datatype and missingvalues

  • type 变成了dtype
  • Series.dtype返回该column的类型
  • 当一个Series全是字符串的时候,它的dtype是object
  • 类型转换astype("float64")

missing data

  • NAN总是float64类型的
  • pd.isnull()
  • pd.notnull()选出含或不含nan的条目
  • pd.fillna()填充,也可以用pd.replace()
    ps:
    reviews_per_region = reviews.region_1.fillna('Unknown').value_counts().sort_values(ascending=False)

6.renaming and combining

reviews.rename(columns={'points': 'score'})#points->score
reviews.rename(index={0: 'firstEntry', 1: 'secondEntry'})#参数很多种,字典最方便
reviews.rename_axis("wines", axis='rows').rename_axis("fields", axis='columns')
行索引和列索引都可以有自己的name属性。可以使用附加的rename_axis()方法来更改这些名称。

combining

pd.concat([canadian_youtube, british_youtube])#沿着特定的轴将其连接起来

left = canadian_youtube.set_index(['title', 'trending_date'])
right = british_youtube.set_index(['title', 'trending_date'])

left.join(right, lsuffix='_CAN', rsuffix='_UK')
'''
The lsuffix(左的重复列名使用的后缀) and rsuffix parameters are necessary here because the data has the same column names in both British and Canadian datasets.
If this wasn't true (because, say, we'd renamed them beforehand) we wouldn't need them.
'''

word

embed:嵌入
syntax:句法,规则
ascend:升高,攀登
intimate:亲密的
well-endowed:天赋好的
property:所有物,特性
syntactically 在语法构成上
novice:初学者
custom:自定义的
built-in:内置的
simultaneously:同时
tiered:阶梯式的,分层的
thereof:其中
complimentary 赞美的
suffix:后缀