运用三种方法(列表、numpy、字典)生成一个DATA Frame
时间: 2023-07-10 07:40:29 浏览: 96
pandas通过字典生成dataframe的方法步骤
好的,下面是三种方法生成DataFrame的示例代码:
使用列表:
```python
import pandas as pd
data = [["Alice", 23, "Female"], ["Bob", 25, "Male"], ["Charlie", 21, "Male"]]
df = pd.DataFrame(data, columns=["Name", "Age", "Gender"])
print(df)
```
输出结果:
```
Name Age Gender
0 Alice 23 Female
1 Bob 25 Male
2 Charlie 21 Male
```
使用NumPy:
```python
import pandas as pd
import numpy as np
data = np.array([["Alice", 23, "Female"], ["Bob", 25, "Male"], ["Charlie", 21, "Male"]])
df = pd.DataFrame(data, columns=["Name", "Age", "Gender"])
print(df)
```
输出结果:
```
Name Age Gender
0 Alice 23 Female
1 Bob 25 Male
2 Charlie 21 Male
```
使用字典:
```python
import pandas as pd
data = {"Name": ["Alice", "Bob", "Charlie"], "Age": [23, 25, 21], "Gender": ["Female", "Male", "Male"]}
df = pd.DataFrame(data)
print(df)
```
输出结果:
```
Name Age Gender
0 Alice 23 Female
1 Bob 25 Male
2 Charlie 21 Male
```
阅读全文