用python对excel表格处理
时间: 2023-09-26 16:11:17 浏览: 98
Python可以使用pandas库来处理Excel表格,以下是一些常见的操作:
1. 读取Excel表格
```python
import pandas as pd
# 读取Excel表格
df = pd.read_excel('example.xlsx')
print(df.head())
```
2. 写入Excel表格
```python
import pandas as pd
# 写入Excel表格
df = pd.DataFrame({'name': ['Alice', 'Bob', 'Charlie'], 'age': [20, 25, 30]})
df.to_excel('example.xlsx', index=False)
```
3. 筛选数据
```python
import pandas as pd
# 筛选数据
df = pd.read_excel('example.xlsx')
filtered_df = df[df['age'] > 25]
print(filtered_df.head())
```
4. 添加新列
```python
import pandas as pd
# 添加新列
df = pd.read_excel('example.xlsx')
df['gender'] = ['female', 'male', 'male']
print(df.head())
```
5. 删除列
```python
import pandas as pd
# 删除列
df = pd.read_excel('example.xlsx')
df.drop(columns=['gender'], inplace=True)
print(df.head())
```
6. 修改列名
```python
import pandas as pd
# 修改列名
df = pd.read_excel('example.xlsx')
df.rename(columns={'name': 'Name', 'age': 'Age'}, inplace=True)
print(df.head())
```
7. 按列排序
```python
import pandas as pd
# 按列排序
df = pd.read_excel('example.xlsx')
df.sort_values(by='age', inplace=True)
print(df.head())
```
以上是一些常用的Excel表格处理操作,pandas库还有很多其他功能,可以根据实际需求进行使用。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![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)
![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)