pandas行列转换
时间: 2023-07-09 09:06:41 浏览: 92
我们可以使用 pandas 中的 `pivot` 和 `melt` 函数来进行行列转换。
假设我们有以下的数据集:
```
+------+--------+-------+
| Name | Gender | Score |
+------+--------+-------+
| Tom | Male | 85 |
+------+--------+-------+
| Amy | Female | 90 |
+------+--------+-------+
| Jim | Male | 75 |
+------+--------+-------+
| Kim | Female | 80 |
+------+--------+-------+
```
我们想要将 `Gender` 列作为行索引,将 `Name` 列作为列索引,将 `Score` 列的值填充到新的表格中。那么我们可以使用 `pivot` 函数来实现:
```python
import pandas as pd
data = {
'Name': ['Tom', 'Amy', 'Jim', 'Kim'],
'Gender': ['Male', 'Female', 'Male', 'Female'],
'Score': [85, 90, 75, 80]
}
df = pd.DataFrame(data)
new_df = df.pivot(index='Gender', columns='Name', values='Score')
```
得到的新表格如下:
```
+--------+------+-----+-----+-----+
| Gender | Amy | Jim | Kim | Tom |
+--------+------+-----+-----+-----+
| Female | 90 | 0 | 80 | 0 |
+--------+------+-----+-----+-----+
| Male | 0 | 75 | 0 | 85 |
+--------+------+-----+-----+-----+
```
如果我们想要将列索引转换成行索引,那么我们可以使用 `melt` 函数来实现:
```python
new_df = new_df.reset_index()
melt_df = pd.melt(new_df, id_vars=['Gender'], var_name='Name', value_name='Score')
melt_df = melt_df[melt_df['Score'] != 0].reset_index(drop=True)
```
得到的新表格如下:
```
+--------+------+-------+
| Gender | Name | Score |
+--------+------+-------+
| Female | Amy | 90 |
+--------+------+-------+
| Female | Kim | 80 |
+--------+------+-------+
| Male | Jim | 75 |
+--------+------+-------+
| Male | Tom | 85 |
+--------+------+-------+
```
以上就是 pandas 行列转换的方法。
阅读全文