pandas之Dataframe 菜鸟教程

import numpy as np
import pandas as pd
print("=============Dataframe:基本概念及创建=====================")
'''
Pandas数据结构Dataframe:基本概念及创建
"二维数组"Dataframe:是一个表格型的数据结构,包含一组有序的列,其列的值类型可以是数值、字符串、布尔值等。
Dataframe中的数据以一个或多个二维块存放,不是列表、字典或一维数组结构。
'''
# Dataframe 数据结构
# Dataframe是一个表格型的数据结构,“带有标签的二维数组”。
# Dataframe带有index(行标签)和columns(列标签)
data={'name':['Jack','Tom','Mary'],
      'age':[18,19,20],
      'gander':['m','m','w']
    }
print(pd.Series(data))
frame=pd.DataFrame(data)
print(frame)
print(frame.index,'\n该数据类型为:',type(frame.index))
print(frame.columns,'\n该数据类型为:',type(frame.columns))
print(frame.values,'\n该数据类型为:',type(frame.values))
# 查看数据,数据类型为dataframe
# .index查看行标签
# .columns查看列标签
# .values查看值,数据类型为ndarray
print("==========Dataframe创建方法====================")
# Dataframe 创建方法一:由数组/列表组成的字典
# 创建方法:pandas.Dataframe()
data1={'a':[1,2,3],
       'b':[3,4,5],
       'c':[4,5,6]}
data2={'one':np.random.rand(3),
       'two':np.random.rand(3)}# 这里如果尝试  'two':np.random.rand(4) 会怎么样?
print(data1)
print(data2)
print(pd.DataFrame(data1))
print(pd.DataFrame(data2))
print('---------------------')
# 由数组/list组成的字典 创建Dataframe,columns为字典key,index为默认数字标签
# 字典的值的长度必须保持一致!
df1=pd.DataFrame(data1,columns=['b','c','a','d'])
df2=pd.DataFrame(data2,columns=['b','c'])
print(df1)
# columns参数:可以重新指定列的顺序,格式为list,如果现有数据中没有该列(比如'd'),则产生NaN值
# 如果columns重新指定时候,列的数量可以少于原数据
df2=pd.DataFrame(data2,index=['f1','f2','f3'])# 这里如果尝试  index = ['f1','f2','f3','f4'] 会怎么样?
print(df2)
# index参数:重新定义index,格式为list,长度必须保持一致
print("==========# Dataframe 创建方法二:由Series组成的字典================")
# Dataframe 创建方法二:由Series组成的字典
data1={'one':pd.Series(np.random.rand(2)),
       'two':pd.Series(np.random.rand(3))}# 没有设置index的Series
data1={'one':pd.Series(np.random.rand(2),index=['a','b']),
       'two':pd.Series(np.random.rand(3),index=['a','b','c'])}# 设置了index的Series
print(data1)
print(data2)
df1=pd.DataFrame(data1)
df2=pd.DataFrame(data2)
print(df1)
print(df2)
# 由Seris组成的字典 创建Dataframe,columns为字典key,index为Series的标签(如果Series没有指定标签,则是默认数字标签)
# Series可以长度不一样,生成的Dataframe会出现NaN值
print("==================创建方法三:通过二维数组直接创建=======================")
# Dataframe 创建方法三:通过二维数组直接创建
ar=np.random.rand(9).reshape(3,3)
print(ar)
df1=pd.DataFrame(ar)
df2=pd.DataFrame(ar,index=['a','b','c'],columns=['one','two','three'])# 可以尝试一下index或columns长度不等于已有数组的情况
print(df1)
print(df2)
# 通过二维数组直接创建Dataframe,得到一样形状的结果数据,如果不指定index和columns,两者均返回默认数字格式
# index和colunms指定长度与原数组保持一致
print("==================创建方法四:由字典组成的列表====================")
data=[{'one':1,'two':2},{'one':5,'two':10,'three':20}]
print(data)
df1=pd.DataFrame(data)
print(df1)
df2=pd.DataFrame(data,index=['a','b'])
print(df2)
df3=pd.DataFrame(data,columns=['one','two'])
print(df3)
# 由字典组成的列表创建Dataframe,columns为字典的key,index不做指定则为默认数组标签
# colunms和index参数分别重新指定相应列及行标签
print("==================创建方法五:由字典组成的字典====================")
# Dataframe 创建方法五:由字典组成的字典
data={'Jack':{'math':90,'english':89,'art':78},
      'Marry': {'math': 82, 'english': 95, 'art': 92},
      'Tom': {'math': 78, 'english': 67}}
df1=pd.DataFrame(data)
print(df1)
# 由字典组成的字典创建Dataframe,columns为字典的key,index为子字典的key
df2=pd.DataFrame(data,columns=['Jack','Tom','Bob'])
df3=pd.DataFrame(data,index=['a','b','c'])
print(df2)
print(df3)
# columns参数可以增加和减少现有列,如出现新的列,值为NaN
# index在这里和之前不同,并不能改变原有index,如果指向新的标签,值为NaN (非常重要!)

print("============Dataframe:索引================")
'''
Pandas数据结构Dataframe:索引
Dataframe既有行索引也有列索引,可以被看做由Series组成的字典(共用一个索引)
选择列 / 选择行 / 切片 / 布尔判断
'''
#选择行和列
df=pd.DataFrame(np.random.rand(12).reshape(3,4)*100,
                index=["one","two","three",],
                columns=["a","b","c","d"])
print(df)
data1=df["a"]
data2=df[["a"]]
print(data1,type(data1))
print(data2,type(data2))
# 按照列名选择列,只选择一列输出Series,选择多列输出Dataframe

data3=df.loc['one']
data4=df.loc[['one','two']]
print(data3)
print(data4)
# 按照index选择行,只选择一行输出Series,选择多行输出Dataframe
print("================df[] - 选择列=================")
# df[] - 选择列
# 一般用于选择列,也可以选择行
df=pd.DataFrame(np.random.rand(12).reshape(3,4)*100,
                index=['one','two','three'],
                columns=['a','b','c','d'])
print(df)
print('==================')
data1=df['a']
data2=df[['b','c']]# 尝试输入 data2 = df[['b','c','e']]
print(data1)
print(data2)
# df[]默认选择列,[]中写列名(所以一般数据colunms都会单独制定,不会用默认数字列名,以免和index冲突)
# 单选列为Series,print结果为Series格式
# 多选列为Dataframe,print结果为Dataframe格式
data3=df[:1]
# data3 = df[0]# df[]中为数字时,默认选择行,且只能进行切片的选择,不能单独选择(df[0])
# data3 = df['one']# df[]不能通过索引标签名来选择行(df['one'])
print("================df.loc[] - 按index选择行=================")
df1=pd.DataFrame(np.random.rand(16).reshape(4,4)*100,
                 index=['one','two','three','four'],
                 columns=['a','b','c','d']
)
df2=pd.DataFrame(np.random.rand(16).reshape(4,4)*100,
                 columns=['a','b','c','d'])
print(df1)
print(df2)
print("======================")
data1=df1.loc['one']
data2=df2.loc[1]
print(data1)
print(data2)
print('单标签索引\n-----')
# 单个标签索引,返回Series
data3=df2.loc[[3,2,1]]
print(data3)
print(data4)
print('多标签索引\n======')
# 多个标签索引,如果标签不存在,则返回NaN
# 顺序可变

data5=df1.loc['one':'three']
data6=df2.loc[1:3]
print(data5)
print(data6)
print('切片索引')
#可以做切片对象
#末端包含
# 核心笔记:df.loc[label]主要针对index选择行,同时支持指定index,及默认数字index
print("============df.iloc[] - 按照整数位置(从轴的0到length-1)选择行===============")
# 类似list的索引,其顺序就是dataframe的整数位置,从0开始计
df=pd.DataFrame(np.random.rand(16).reshape(4,4)*100,
         index=['one','two','three','four'],
        columns=['a','b','c','b'])
print(df)
print("===================")
print(df.iloc[0])
print(df.iloc[-1])
#print(df.iloc[4],"============")
# 单位置索引
# 和loc索引不同,不能索引超出数据行数的整数位置
print(df.iloc[[0,2]])
print(df.iloc[[3,2,1]])
print('多位置索引\n=========')
# 多位置索引
# 顺序可变
print(df.iloc[1:3])
print(df.iloc[::2])
# 切片索引
# 末端不包含
print("==============# 布尔型索引================")
# 布尔型索引
# 和Series原理相同
df=pd.DataFrame(np.random.rand(16).reshape(4,4)*100,
                index=['one','two','three','four'],
                columns=['a','b','c','d']
                )
print(df)
print(df.loc['one','a'])
print(df.loc[['one','two'],['a','b']])
print(df.loc['one':'three','a':'c'])
print(df.loc[:,'a':'c'])
print("================")

b1=df<20
print(b1,type(b1))
print(df[b1])# 也可以书写为 df[df < 20]
print("============")
# 不做索引则会对数据每个值进行判断
# 索引结果保留 所有数据:True返回原数据,False返回值为NaN
b2=df['a']>50
print(b2,type(b2))
print(df[b2])# 也可以书写为 df[df['a'] > 50]


print(df)
b3=df[['a','b']]>50
print(b3,type(b3))
print(df[b3])
print("===============")
# 多列做判断
# 索引结果保留 所有数据:True返回原数据,False返回值为NaN

print(df)
b4 = df.loc[['one','three']] < 50
print(b4,type(b4))
print(df[b4])  # 也可以书写为 df[df.loc[['one','three']] < 50]
print('----------------------------------------------------')
# 多行做判断
# 索引结果保留 所有数据:True返回原数据,False返回值为NaN

print("=======loc/iloc[]补充============")
#loc[行索引名称,列索引名称]
#iloc[行索引位置,列索引位置]
df = pd.DataFrame(np.random.rand(16).reshape(4,4)*100,
                  index=['one','two','three','four'],
                  columns=['a','b','c','d'])
print(df)
print(df.loc['one','a'])
print(df.loc[['one','two'],['c','d']])
print(df.loc['one':'three',['b','d']])
print(df.loc[:,'b':'c'])
print(df.loc['one',:])
print('--------------------')
print(df)
print(df.iloc[1,1])
print(df.iloc[[0,1],[2,3]])
print(df.iloc[0:2,2:4])
print(df.iloc[:,2:4])
print("==================多重索引=====================")
df = pd.DataFrame(np.random.rand(16).reshape(4,4)*100,index=['one','two','three','four'],columns=['a','b','c','d'])
print(df)
print(df.iloc[[0,2],0])
print(df.loc[['one','three'],'a'])
print(df['a'].loc[['one', 'three']])
print(df[['b','c','d']].iloc[::2])
print(df[df['a'] < 50].iloc[:2])

print("=======================pandas官网学习============================")
dates = pd.date_range('20130101', periods=6)
print(dates, type(dates))
df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list('ABCD'))
print(df)
print(df.head(3))
print(df.to_numpy())
print(df.describe())
print(df)
print(df.sort_index(axis=1, ascending=False))
print(df.sort_index(axis=0, ascending=False))
print(df.sort_values(by='B',ascending=False))
print(dates[0])
print(df.loc[dates[0]])
df2 = df.copy()
print(df2)
df2['E'] = ['one', 'one', 'two', 'three', 'four', 'three']
print(df2)
print(df2['E'].isin(['two', 'four']))
print(df2[df2['E'].isin(['two', 'four'])])
s1 = pd.Series([1, 2, 3, 4, 5, 6], index=pd.date_range('20130102', periods=6))
print(s1)
print(df)
df['F'] = s1
print(df)
df.at[dates[0], 'A'] = 0
print(df)
df.iat[0, 1] = 0
print(df)
df.loc[:, 'D'] = np.array([5] * len(df))
print(df)
df1 = df.reindex(index=dates[0:4], columns=list(df.columns) + ['E'])
print(df1)
df1.loc[dates[0]:dates[1], 'E'] = 1
print(df1)
print(df1.dropna(how='any'))
print(df1.fillna(value=5))
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林中有神君

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值