相关资料:
- pandas 基础用法大全(入门首选)
- chatgpt
读与构建
import pandas as pd
import os
read_path = './data/习题.xlsx'
data = pd.read_excel(read_path, engine="openpyxl") # 通过文件加载
data = pd.read_excel(read_path , engine="openpyxl", header=1) # 第2行(index=1)作为列索引
new_excal = pd.DataFrame() # 空的
读取
a = data.iat[row, col] # 第row行,第col列
data.iloc[:3,:2] #冒号前后的数字不再是索引的标签名称,而是数据所在的位置,从0开始,前三行,前两列。
print(data.loc[3]) # 提取下标为3的一整行
print(data.iloc[0:5]) # 提取下标为[0,5)的整行
print(data.loc[:,['景点名称', '推荐', '评分']])
print(data.loc[row]['景点名称']) # row为col_index, 即第row行,'景点名称'为列索引
修改数据
data.iat[row, col] = a + 1 # 修改第row行,第col列, 如果该行列原来不存在,报越界
new_excal.loc[row, col] = vv # 在第row行,第col列填入新数据
修改索引
1、修改列名a,b为A、B。
df.columns = ['A','B']
2、只修改列名a为A
df.rename(columns={'a':'A'})
保存
new_excal.to_excel('excel_to_python.xlsx')
new_excal.to_excel('excel_to_python.xlsx', sheet_name='bluewhale_cc', index=False, columns=True) # index,columns表示是否保留行或者列索引,这里是不要行索引,保留列索引
new_excal.to_csv('excel_to_python.csv')
字符串查找
if tigan.find('()') == -1:
tigan += '()。'
else:
tigan += '。'
分组排序
data = pd.read_excel('./data/习题.xlsx', engine="openpyxl", header=1) # 通过文件加载
print(data.head)
print(data.shape)
print(data.columns)
row, col = data.shape
# # 首先按照题型进行分组
# grouped = data.groupby('题型')
# # 定义一个函数,用于在每个分组内按照章节进行排序
# def sort_by_chapter(group):
# return group.sort_values(by='章节')
# # 对每个分组应用排序函数
# sorted_df = grouped.apply(sort_by_chapter)
# # 重置索引
# sorted_df.reset_index(drop=True, inplace=True)
# print(sorted_df)
# 指定题型的排序顺序
custom_order = ["单选题", "多选题", "判断题", "主观题"]
data['题型'] = pd.Categorical(data['题型'], categories=custom_order, ordered=True)
# 按照"题型"和"章节"两列进行排序
sorted_df = data.sort_values(by=['题型', '章节']).reset_index(drop=True) # 重置索引
data = sorted_df
正则表达式匹配
复杂一点的请交给chatgpt
吧。
如何下一个python的正则表达式代码,替换下面字符串的题号:“1、这是一个题目。”
import re
text = "1、这是一个题目。"
pattern = r'^\d+、' # 匹配以数字和一个逗号开头的模式
# 使用re.sub()函数进行替换
result = re.sub(pattern, '', text)
print(result)