python日记Day17——Pandas之Excel处理

python日记——Pandas之Excel处理

  • 创建文件
import pandas as pd
df = pd.DataFrame({
   'ID':[1,2,3],'Name':['Tom','BOb','Gigi']})
df.to_excel("C:/Temp/Output.xlsx")
print("done!")
  • 读取文件
import pandas as pd
people = pd.read_excel("C:/Temp/people.xlsx",index_col='ID')
#index_col用于设置索引
print(people.shape)
print(people.columns)
print(people.index)
print(people.head(3))#打印前三行,默认5行
print(people.tail(3))#打印后三行,默认5行

当head比较“脏”,即第一行不是表头时:

people = pd.read_excel("C:/Temp/people.xlsx",header=1)
#header的值由表头的位置决定
#当第一行为空时,不需要设置header,自动跳过空行

当表在其他位置时,如何读取:

people = pd.read_excel('C:/Temp/people.xlsx',skiprows=3,usecols="C:F")
#skiprows用于跳过行,usecols用于规定列

当没有表头时,可自行进行设置:

people.columns = ['序号','姓名','年龄']

当创建一个新的表格时,会生成自动索引,怎样去掉默认的自动索引:

people = people.set_index("序号")
#people.set_index("序号",inplace=True)
  • 行、列、单元格
    pandas的Serise对象可以当作Excel中的一列,由此可以根据Serise创建Excel:
import pandas as pd
A = pd.Series([1,2,3],index=[1,2,3],name="A")
B = pd.Series([10,20,

你可能感兴趣的:(Python笔记,excel,python,数据分析)