pandas库常用代码
时间: 2024-06-13 11:03:20 浏览: 23
Pandas是Python中一个强大的数据处理和分析库,它提供了丰富的数据结构和高效的数据操作工具。以下是一些Pandas库中常用的代码片段:
1. **导入Pandas库**:
```python
import pandas as pd
```
2. **创建DataFrame(表格结构)**:
```python
data = {'column1': [1, 2, 3], 'column2': ['a', 'b', 'c']}
df = pd.DataFrame(data)
```
3. **读取CSV文件**:
```python
df = pd.read_csv('file.csv')
```
或者使用内存中的数据:
```python
df = pd.DataFrame({'values': [1, 2, 3, 4, 5]})
```
4. **查看数据前几行**:
```python
df.head()
```
5. **筛选数据(基于条件)**:
```python
df[df['column'] > 10]
```
6. **分组和聚合数据**:
```python
df.groupby('column1').sum()
```
7. **合并或连接数据集**:
```python
pd.merge(df1, df2, on='key_column')
```
8. **排序数据**:
```python
df.sort_values('column_name', ascending=False)
```
9. **数据清洗(缺失值处理)**:
```python
df.dropna() # 删除缺失值
df.fillna(value) # 填充缺失值
```
10. **数据透视表(数据汇总)**:
```python
df.pivot_table(values='column', index='index_column', columns='column_to_group_by')
```
相关推荐
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)