python 写入并打开excel score_df.to_excel
时间: 2023-06-14 22:03:30 浏览: 163
可以使用 pandas 库中的 to_excel 方法将 DataFrame 对象写入 Excel 文件中,代码如下:
```python
import pandas as pd
# 假设你的 DataFrame 对象名为 score_df
score_df.to_excel('scores.xlsx', sheet_name='Sheet1', index=False)
# 读取保存的 Excel 文件
new_score_df = pd.read_excel('scores.xlsx', sheet_name='Sheet1')
```
其中,to_excel 方法接收三个主要参数:
- file_path:Excel 文件的保存路径
- sheet_name:写入的工作表名称,默认为 Sheet1
- index:是否在写入时包含 DataFrame 的索引,默认为 True
读取 Excel 文件时,也可以指定 sheet_name 参数选择读取哪个工作表。
相关问题
创建一个Python脚本,命名为 score_analyse.py ,完成以下功能: 1.读取以下4位同学的成绩并用一个数据框变量 df 来保存,其中成绩如下,需要自己新建又本文件保存,并命名为 score.txt: 姓名,科目,成绩 小红,语
创建名为 `score_analyse.py` 的 Python 脚本,首先,你需要创建一个文本文件 `score.txt` 并输入数据。以下是脚本的基本结构,用于读取文本文件并将其转换为 pandas DataFrame:
```python
# 导入必要的库
import pandas as pd
# 定义函数来读取数据
def read_scores_from_file(filename):
with open(filename, 'r') as file:
lines = file.readlines()
# 使用逗号分隔数据
data_list = [line.strip().split(',') for line in lines]
# 创建 DataFrame
df = pd.DataFrame(data_list[1:], columns=data_list[0]) # 假设第一行是列名
return df
# 创建数据文件
if __name__ == "__main__":
# 确保文件存在或者创建它
if not os.path.isfile('score.txt'):
with open('score.txt', 'w') as f:
f.write("姓名,科目,成绩\n") # 写入表头
f.write("小红,语文,95\n")
f.write("小明,数学,98\n")
f.write("小芳,英语,90\n")
f.write("小刚,物理,92\n")
# 读取数据
df = read_scores_from_file('score.txt')
# 打印 DataFrame 或者做进一步分析
print(df)
#
2、有一个学生成绩的文件score.txt,包括学号、姓名、行政班号、课前、课中、课后的成绩, 读取文件,并计算该学生平时成绩并写入到score_new.txt。
假设score.txt的格式如下:
```
学号 姓名 行政班号 课前成绩 课中成绩 课后成绩
1001 张三 1班 80 90 95
1002 李四 2班 75 85 90
1003 王五 1班 85 90 92
```
可以使用Python的pandas库来读取和处理数据。代码如下:
```python
import pandas as pd
# 读取score.txt文件
df = pd.read_csv('score.txt', sep=' ', header=None, names=['学号', '姓名', '行政班号', '课前成绩', '课中成绩', '课后成绩'])
# 计算平时成绩
df['平时成绩'] = (df['课前成绩'] + df['课中成绩'] + df['课后成绩']) / 3
# 写入score_new.txt文件
df.to_csv('score_new.txt', sep=' ', index=False)
```
运行以上代码后,会生成一个新的score_new.txt文件,其格式如下:
```
学号 姓名 行政班号 课前成绩 课中成绩 课后成绩 平时成绩
1001 张三 1班 80 90 95 88.333333
1002 李四 2班 75 85 90 83.333333
1003 王五 1班 85 90 92 89.000000
```
其中,新增了一列“平时成绩”,表示每个学生的平时成绩。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)