[Python--pandas] pandas reads and writes csv files---overview

Use pandas to read, save and simple operations of csv files

1. The original file format is as follows

Insert picture description here

import pandas as pd

2. File reading

data = pd.read_csv('学生月考成绩表.csv',header = None) #header注明data是否包含有标题行
data

Insert picture description here

data = pd.read_csv('学生月考成绩表.csv') #header注明data是否包含有标题行
data

Insert picture description here

3. Read and change the data in the table

1) The reading of data takes loc as an example
data.loc[0] #选取第0行元素

Insert picture description here

data.loc[0,'Math'] #选取第0行/第Math列元素

Insert picture description here
1) loc, based on the column label, can select a specific row (according to the row index);
2) iloc, based on the row/column position;
3) at, quickly locate the elements of the DataFrame according to the specified row index and column label;
4) iat , Similar to at, the difference is based on position;
5) ix, a mixture of loc and iloc, supports both label and position. Reference from [1]

2) Modification of specific values
data.shape #获取数据DataFreme格式的大小

Insert picture description here

data.iat[0,6] = 100 #将数据的第0行第6列修改为100
data

Insert picture description here

data.rename(columns={
    
    'Nmae':'Name'},inplace=True) #修改列名称
data

Insert picture description here

4. Insert and delete rows and columns

1) Add in the last line
newrow = pd.DataFrame({
    
    'Name':'lisi','Chinese':30,'Math':40,'English':50,'Science':60,'Score':70,'Ranking':6},index=[0]) #设置行标index=[0]
data = data.append(newrow,ignore_index=True)#忽略行标设置
data

Insert picture description here

2) Modify the line at the specified location
data.loc[2] = ['wangwu',30,40,50,60,70,6] #修改第2行的值
3) Add a column at the specified position
data.insert(1,'Art',[80,81,82,83,85])    #插入一列
data

Insert picture description here

3) Delete rows or columns
data.drop('Math', axis=1, inplace=True) #删除Math列,axis为1表示删除列,0表示删除行。inplace为True表示直接对原表修改。
data.drop(0, axis=0, inplace=True)#删除第0行,axis为1表示删除列,0表示删除行。inplace为True表示直接对原表修改。
data

Insert picture description here

5. The index of the element position in the table

index = data[data.Ranking == 3].index.tolist()
index

Insert picture description here

6. Save the file

data.to_csv('student_score.csv',index=False) #index = False取消行名称,header = None则取消列名称

Insert picture description here

reference

【1】https://blog.csdn.net/grllery/article/details/81292085
【2】https://blog.csdn.net/huang_susan/article/details/80626698
【3】https://blog.csdn.net/u010801439/article/details/80033341

Guess you like

Origin blog.csdn.net/qq_22290797/article/details/104706093