python pandas

Created

2024-10-28 13:40:37

Updated

2024-10-28 13:40:45

1 创建excel

1.1 创建空excel

import pandas as pd
file = "output.xlsx"

# 简单创建一个xlsx文件
df = pd.DataFrame()
# 保存到目录下,内容是空的
df.to_excel("output.xlsx")

1.2 创建带数据的excel

  • 会在最左边一列显示0 1 2,是dataFrame的索引
import pandas as pd
df = pd.DataFrame({"id": [11, 22, 33], "name": ["xiaobai", "xiaohong", "xiaohei"]})
df.to_excel("output.xlsx")
id name
0 11 xiaohei
1 22 xiaohong
2 33 xiaobai
  • 将id 设置为df的索引, 这样生成的excel 不会在前面用自动生成0 1 2..
df = pd.DataFrame({"id": [11, 22, 33], "name": ["xiaobai", "xiaohong", "xiaohei"]})
df = df.set_index("id")
df.to_excel("output.xlsx") # (1)
id name
11 xiaohei
22 xiaohong
33 xiaobai

2 读取excel

id name
11 xiaohei
22 xiaohong
33 xiaobai
44 xiaohuang
55 xiaolan
66 xiaozi
import pandas as pd
file = "input.xlsx"
user = pd.read_excel(file)
# 打印几行几列
# (6, 2): 6行2列的意思,注意不包含列名那一行
print(user.shape)
print(user.columns) # 打印列名(表头)
print(user.head())  #默认打印5行
print(user.head(5)) # 读5行

输出的结果: 加上列名那一行,一共6行, 第一列是索引列

    id       name
0  11    xiaobai
1  22   xiaohong
2  33    xiaohei
3  44  xiaohuang
4  55    xiaolan
import pandas as pd
file = "input.xlsx"
# 直接指定哪列是index, 这样获取的数据就不会有自动生成的那个索引列
user = pd.read_excel(file, index_col="id")
print(user.head())
id       name
11    xiaobai
22   xiaohong
33    xiaohei
44  xiaohuang
55    xiaolan
import pandas as pd
file = "input.xlsx"
# 如果 表格前面的行是空的, 会自动跳过的
# 如果 是脏数据, 就需要指定了
# 从excel的第二行开始读 (这个时候第二行作为列名行)
user = pd.read_excel(file, header=1)
print(user.columns) # 这个时候的列名是 上面读取的第一行
Index([11, 'xiaobai'], dtype='object')
import pandas as pd
file = "input.xlsx"
# 没有header的情况,就是我们没有给表格的表头指定是什么字段
# 没有列名, 全是数据, 那么我们就要
user = pd.read_excel(file, header=None)
print(user.columns) # 默认会给表头指定为 0,1,2..
Int64Index([0, 1], dtype='int64')
user = pd.read_excel(file)
user.columns = ["user_id", "user_name"]
# inplace=True 表示直接修改, 否则你需要 user=user.set_index("user_id")
user.set_index("user_id",inplace=True) # 这样就不会输出 默认的索引列, 用user_id作为索引了.
user.to_excel("output5.xlsx")
user_id user_name
11 xiaohei
22 xiaohong
33 xiaobai
44 xiaohuang
55 xiaolan
66 xiaozi

3 统计

4 排序

5 数据筛选

Back to top