利用pandas库完成2项编程任务。 (1)利用列表、元组和字典分别创建3个一级索引的数据结构Series。 (2)利用字典和Series分别创建2个二级索引的数据结构DataFrame
时间: 2023-06-25 14:07:08 浏览: 142
(1) 利用列表、元组和字典分别创建3个一级索引的数据结构Series:
```python
import pandas as pd
# 列表创建Series
list_data = [10, 20, 30, 40]
list_index = ['a', 'b', 'c', 'd']
list_series = pd.Series(list_data, index=list_index)
print(list_series)
# 元组创建Series
tuple_data = (10, 20, 30, 40)
tuple_index = ('a', 'b', 'c', 'd')
tuple_series = pd.Series(tuple_data, index=tuple_index)
print(tuple_series)
# 字典创建Series
dict_data = {'a': 10, 'b': 20, 'c': 30, 'd': 40}
dict_series = pd.Series(dict_data)
print(dict_series)
```
输出结果:
```
a 10
b 20
c 30
d 40
dtype: int64
a 10
b 20
c 30
d 40
dtype: int64
a 10
b 20
c 30
d 40
dtype: int64
```
(2) 利用字典和Series分别创建2个二级索引的数据结构DataFrame:
```python
# 字典创建DataFrame
data = {'name': pd.Series(['Alice', 'Bob', 'Charlie']),
'age': pd.Series([25, 30, 35]),
'gender': pd.Series(['F', 'M', 'M'])}
df_dict = pd.DataFrame(data)
print(df_dict)
# Series创建DataFrame
name = pd.Series(['Alice', 'Bob', 'Charlie'])
age = pd.Series([25, 30, 35])
gender = pd.Series(['F', 'M', 'M'])
data = {'name': name, 'age': age, 'gender': gender}
df_series = pd.DataFrame(data)
print(df_series)
```
输出结果:
```
name age gender
0 Alice 25 F
1 Bob 30 M
2 Charlie 35 M
name age gender
0 Alice 25 F
1 Bob 30 M
2 Charlie 35 M
```
阅读全文