05 pandas DataFrame_删改查、索引器、读写文件

=== 获取内容 ===

import pandas as pd
import numpy as np
stu_info = pd.read_excel('student_info1.xlsx',sheetname='countif').head(5)
stu_info

1、 取列

# 单列
stu_info['语文']
# 多列
stu_info[['数学','语文']]

2、 切片

# 行切片
stu_info1 = stu_info[0:3]
stu_info1
# 列切片 使用转置
stu_info.T[0:3].T

3、使用索引器
注意: stu_info1 = stu_info.ix[0] #版本更新可能会删除ix,使用loc或iloc代替

# loc[行,列] [a,A] [a:c,B:D] [[a,b,g],[R,E,A]]
stu_info.loc[0:2,'数学':'语文']

iloc[行下标,列下标] ,不再赘述

=== DataFrame 增删改 ===

1、学号2~3的人,语文成绩加10分

stu_info = pd.read_excel('student_info1.xlsx',sheetname='countif',index_col='学号').head(5)
#stu_info.loc[1:3,'语文']= stu_info.loc[1:3,'语文']+10
stu_info.loc[1:3,'语文']+=10
stu_info

2、修改一个人的全部成绩

stu_info = pd.read_excel('student_info1.xlsx',sheetname='countif',index_col='学号').head(5)
stu_info.loc[3] = [22,22,44] 
stu_info

3、新增行、删除行

# 新增行
stu_info = pd.read_excel('student_info1.xlsx',sheetname='countif',index_col='学号').head(5)
stu_info.loc[6] = [33,33,66] 
stu_info

# 删除行
stu_info = stu_info.drop([1,3,5])
stu_info

# 删除列
stu_info = stu_info.drop('语文',axis=1)
stu_info

=== 写入文件 ===

# 写文件
stu_info.to_csv("output.csv")
# 读文件
stu_info1 = pd.read_csv('output.csv',encoding='gb2312')
stu_info1
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容