1、
学习原网址:https://www.pypandas.cn/docs/getting_started/10min.html
2、
import numpy as np
import pandas as pd
# 生成对象
s = pd.Series([1, 3, 5, np.nan, 6, 8])
# print(s)
dates = pd.date_range('20130101', periods=6)
# print(dates)
df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))
# print(df)
df2 = pd.DataFrame({'A': 1.,
'B': pd.Timestamp('20130102'),
'C': pd.Series(1, index=list(range(4)), dtype='float32'),
'D': np.array([3] * 4, dtype='int32'),
'E': pd.Categorical(["test", "train", "test", "train"]),
'F': 'foo'})
print(df2.dtypes) #DataFrame 的列有不同数据类型
# 查看数据
print(df.head()) #查看前五行
print(df.tail(3)) ##看后三行
print(df.index) #显示索引
print(df.columns) #显示列名
print(df2.describe()) #可以快速查看数据的统计摘要,mean/srd/min/max/25%
print(df.T) #转置数据
print(df.sort_index(axis=1,ascending=False)) #按轴排序
print(df.sort_values(by="B")) #按B列值排序
# 选择
print(df["A"])
print(df[0:3]) #查看前3行
print(df['20130102':'20130104']) #查看索引为20130102~20130104的行
# 按标签选择
print(df.loc[dates[0]]) ##查看第1行
print(df.loc[:,["A","B"]]) #查看AB列
print(df.loc['20130102', ['A', 'B']])
df.loc[dates[0], 'A']
df.at[dates[0], 'A'] ##同上
# 按位置选择
print(df.iloc[3]) ##查看第4行
print(df.iloc[3:5,0:2]) ##第4、5行,第一第二列
print(df.iloc[[1, 2, 4], [0, 2]]) ##第2、3、5行。第1、3列
print(df.iloc[1, 1]) ##第2行第2列
df.iat[1, 1] ##同上
# 布尔索引
print(df[df.A > 0]) ##显示A列大于0的行
print(df[df >0]) ##显示表中大于0的值,小于0替换成NaN
# 用 isin() 筛选
df2 = df.copy()
df2['E'] = ['one', 'one', 'two', 'three', 'four', 'three']
print(df2)
print(df2[df2["E"].isin(["two","four"])]) ##显示E列为two,four的行
# 按标签赋值:
df.at[dates[0],"A"] = 0 ##第1行的A列,赋值
# 按位置赋值
df.iat[0,1] = 0 ##第1行第2列
# 用 where 条件赋值:
df2 = df.copy()
df2[df2 > 0] = -df2 ##将正数取反
print(df2)
# 缺失值
# Pandas 主要用 np.nan 表示缺失数据。 计算时,默认不包含空值.
# 重建索引(reindex)可以更改、添加、删除指定轴的索引,并返回数据副本,即不更改原数据。
df1 = df.reindex(index=dates[0:4], columns=list(df.columns) + ['E'])
df1.loc[dates[0]:dates[1], 'E'] = 1
print(df1)
df1.dropna(how='any') # #删除所有含缺失值的行
df1.fillna(value=5) ##填充缺失值,将NaN都替换成5
pd.isna(df1) #提取 nan 值的布尔掩码,每个位置标注False ,True
#使用dropna删除某列为空的行
df1 = pd.read_excel('moviedata.xlsx')
df1 = df1.dropna(subset=["豆瓣评分","评分人数"]) #删除指定列空值的行
# 运算
df.mean() #对每列求平均值
df.mean(1) #对每行求平均值
s = pd.Series([1, 3, 5, np.nan, 6, 8], index=dates).shift(2)
print(s)
print(df.sub(s, axis='index'))
# Apply 函数
print(df.apply(np.cumsum))
print(df.apply(lambda x: x.max() - x.min())) #每列最大值-最小值,每列给出一个差值
# 字符串方法
s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat'])
s.str.lower() ##将大写字母变成小写
# 结合(Concat)
df = pd.DataFrame(np.random.randn(10, 4))
print(df)
pieces = [df[:3], df[3:7], df[7:]] # 分解为多组
pd.concat(pieces) ##按行合并
# 连接(join)
left = pd.DataFrame({'key': ['foo', 'foo'], 'lval': [1, 2]})
right = pd.DataFrame({'key': ['foo', 'foo'], 'rval': [4, 5]})
pd.merge(left, right, on='key') ##依据key列名,进行行合并
# 追加(Append)
df = pd.DataFrame(np.random.randn(8, 4), columns=['A', 'B', 'C', 'D'])
print(df)
s = df.iloc[3] #取第三行
print(df.append(s,ignore_index=True)) ##在最后一行追加上第三行
##分组(Grouping)
df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
'foo', 'bar', 'foo', 'foo'],
'B': ['one', 'one', 'two', 'three',
'two', 'two', 'one', 'three'],
'C': np.random.randn(8),
'D': np.random.randn(8)})
print(df)
print(df.groupby("A").sum()) ##对A列分成两组,统计C/D的列的和
print(df.groupby(['A', 'B']).sum())
网友评论