import pandas as pd import numpy as np data = np.arange(100,109).reshape(3,-1) df1 = pd.Dataframe(data) print(df1)
第一行012理解为列名,第一列012理解为索引
自定义data
data1 = {
'name':['Brett','Eddy','Kris'],
'age':[19,18,19],
'habit':['violin','violin','voice']
}
df2=pd.Dataframe(data1)
print(df2)
初始化
自定义列名,自定义索引
df3=pd.Dataframe(data1,columns=['userName','age','habit','height'],index=range(1,4)) print(df3)
userName与data1中的name没有对应关系
索引从0开始,到3(不包括)结束,步进为1
2 获取列名、获取索引
colname = df2.columns indexname = df2.index print(colname,'n',indexname)
3 pandas中数据选取 按列取数Index([‘name’, ‘age’, ‘habit’], dtype=‘object’)
RangeIndex(start=0, stop=3, step=1)
ser=df3.age #取age列的数据 lis=df3[['age']] #以dataframe形式取age列数据 print(ser,'n',lis)
1 19
2 18
3 19
Name: age, dtype: int64
lis=df3[['age','habit']] print(lis)
将某列数据取出后单独处理,须使用copy方法,否则会影响原表
names=df2.name.copy() #copy单独复制数据,不会影响df2 names[0]='jack' print(names,'n',df2)
0 jack
1 Eddy
2 Kris
Name: name, dtype: object
names=df3.userName #会直接影响df3 names[1]='jack' print(df3)
切片
lis2=df3[df3.columns[1:3]] #取出2、3列的所有值 print(lis2)
添加列
df2['height']=[1.67,1.66,1.70] #添加height列 print(df2)
删除列
不影响原表,从原表取出数据drop
lis3=df3.drop(['userName','height'],axis=1) print(lis3,'n',df3)
或按列取数
lis3=df3.drop(df3.columns[1::2],axis=1) print(lis3)
按行索引取数
a=df3.loc[1] #取出行索引为1的数据,series alist=df3.loc[[1,3]] #以dataframe格式取出行索引为1,3的数据 print(a,'n',alist)
userName jack
age 19
habit violin
height 1.67
Name: 1, dtype: object
在不知道行索引前提下,想取出最后两个数据的username和age
lis4=df3.loc[df3.index[-2:],['userName','age']] #df3.index[-2:]查出最后两位索引值 print(lis4)
插入行数据
在最后一行出入自定义数据
df2.loc[df2.shape[0]]={'age':13,'name':'Jordan','habit':'compose'}
print(df2)
删除行
lis5=df2.drop(2) print(lis5) lis5.index=range(lis5.shape[0]) #重置索引编号 print(lis5)
删除行后无原索引也被删除
iloc对象可通过内存中物理顺序取值
lis5=df2.drop(2) print(lis5) b=lis5.iloc[2] #iloc内存中存储的物理顺序 print(b)
name Jordan
age 13
habit compose
Name: 3, dtype: object



