
设置行索引 创建DataFrame时如果不指定行索引pandas会自动添加从0开始的索引。通过set_index()设置行索引- inplace 是否进行原地操作- 如果值是True直接在原有DataFrame上进行修改- 如果值是False返回的是新创建DataFrame对象通过reset_index()重置行索引修改行索引名和列名第一写法通过rename()修改行索引名和列名第二写法将index和columns重新赋值添加列通过 df[“新的列名”] 添加列。删除行列- df.drop(删除目标, axis参数)- axis1 → 删 列column- axis0 → 删 行index插入列通过 insert(loc, column, value) 插入。该方法没有inplace参数直接在原数据上修改。loc → 插在第几列column → 新列叫什么value → 这一列填什么数据importpandasaspdimportnumpyasnpimportmatplotlib.pyplotasplt 本节类似mysql的表结构的修改 #设置行索引 创建DataFrame时如果不指定行索引pandas会自动添加从0开始的索引。defsetRowIndexDefault():dfpd.DataFrame({age:[20,30,40,10],name:[张三,李四,王五,赵六],id:[101,102,103,104]})print(df)# 通过set_index()设置行索引# inplace 是否进行原地操作# 如果值是True直接在原有DataFrame上进行修改# 如果值是False返回的是新创建DataFrame对象defsetRowIndexBySetIndex():dfpd.DataFrame({age:[20,30,40,10],name:[张三,李四,王五,赵六],id:[101,102,103,104]})print(df)print()# 设置行索引df.set_index(id,inplaceTrue)# 如果值是True直接在原有DataFrame上进行修改print(df)# 通过reset_index()重置行索引defsetRowIndexByReSetIndex():dfpd.DataFrame({age:[20,30,40,10],name:[张三,李四,王五,赵六],id:[101,102,103,104]},index[111,122,133,144])print(df)print()df.reset_index(inplaceTrue)# 重置索引print(df)# 修改行索引名和列名defupdateRowIndexAndColumnName():dfpd.DataFrame({age:[20,30,40,10],name:[张三,李四,王五,赵六],id:[101,102,103,104]})print(df)# 第一写法通过rename()修改行索引名和列名df.set_index(id,inplaceTrue)print(df)df.rename(index{101:一,102:二,103:三,104:四},columns{age:年龄,name:姓名},inplaceTrue)print(df)# 家庭作业# 第二写法将index和columns重新赋值# df.set_index(id, inplaceTrue)# print(df)# df.index [Ⅰ, Ⅱ, Ⅲ, Ⅳ]# df.columns [年齡, 名稱]# print(df)# 添加列defaddColumn():dfpd.DataFrame({age:[20,30,40,10],name:[张三,李四,王五,赵六],id:[101,102,103,104]})print(df)# 通过 df[“新的列名”] 添加列。df[phone][1111,2222,3333,4444]print(df)# 删除行列# df.drop(删除目标, axis参数)# axis1 → 删 列column# axis0 → 删 行indexdefdelColumn():dfpd.DataFrame({age:[20,30,40,10],name:[张三,李四,王五,赵六],id:[101,102,103,104]})# 通过 df[“列名”] 添加列。df[phone][1111,2222,3333,4444]print(df)print()#通过df.drop(“列名”, axis 1) 删除print(删除phoneaxis1 →删 列column\n,df.drop(phone,axis1))#删除行删第0行print(删除索引0的行\n,df.drop(0,axis0))# 插入列definsertColumn():# 通过 insert(loc, column, value) 插入。该方法没有inplace参数直接在原数据上修改。# loc → 插在第几列# column → 新列叫什么# value → 这一列填什么数据dfpd.DataFrame({age:[20,30,40,10],name:[张三,李四,王五,赵六],id:[101,102,103,104]})print(df)print()# 在原表格最左边(loc0)插入一列叫 phone值 年龄 × 行号索引df.insert(loc0,columnphone,valuedf[age]*df.index)print(df)if__name____main__:#setRowIndexDefault()#setRowIndexBySetIndex()#setRowIndexByReSetIndex()#updateRowIndexAndColumnName()#addColumn()#delColumn()insertColumn()