将list或numpy array或dict转为pd.Series。 python
时间: 2024-03-01 10:49:40 浏览: 146
你可以使用 pandas 库中的 Series() 函数将 list、numpy array 或 dict 转换为 Pandas 的 Series 数据类型,示例如下:
将 list 转为 Series:
```python
import pandas as pd
my_list = [1, 2, 3, 4, 5]
my_series = pd.Series(my_list)
print(my_series)
```
将 numpy array 转为 Series:
```python
import numpy as np
import pandas as pd
my_array = np.array([1, 2, 3, 4, 5])
my_series = pd.Series(my_array)
print(my_series)
```
将 dict 转为 Series:
```python
import pandas as pd
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
my_series = pd.Series(my_dict)
print(my_series)
```
以上代码都会输出类似如下的 Series 对象:
```
0 1
1 2
2 3
3 4
4 5
dtype: int64
a 1
b 2
c 3
d 4
e 5
dtype: int64
```
相关问题
pandas.Series
### Pandas Series 的使用方法和属性
#### 创建 Series 对象
可以通过多种方式创建 `pandas.Series` 对象。最常见的方式是从 Python 字典或列表创建。
```python
import pandas as pd
# 从字典创建
data_dict = {'语文': 100, '数学': 150}
series_from_dict = pd.Series(data=data_dict)
# 从列表创建
data_list = [30, 40, 50]
series_from_list = pd.Series(data_list)
```
#### 查看 Series 属性
一旦创建了 `Series` 对象,可以访问其多个有用属性来获取有关该对象的信息:
- **shape**: 返回系列的形状,即元素的数量元组形式。
```python
series_shape = series_from_dict.shape # 输出: (2,)
```
- **size**: 获取序列中元素的总数目。
```python
element_count = series_from_dict.size # 输出: 2
```
- **index**: 访问索引标签。
```python
index_labels = series_from_dict.index # 输出: Index(['语文', '数学'], dtype='object')
```
- **values**: 提取底层数值数组。
```python
underlying_array = series_from_dict.values # 输出: array([100, 150])
```
- **name**: 设置或返回整个序列的名字。
```python
named_series = pd.Series({'Hobby': 'Basketball', 'Age': 30}, name='Jack')
print(named_series.name) # 输出: Jack
```
#### 数据操作与统计分析
除了基础属性外,`Series` 还支持一系列强大的内置函数来进行数据处理和统计计算:
- **describe()**: 自动生成描述性统计数据摘要[^1]。
```python
summary_statistics = series_from_list.describe()
```
- **unique()**: 取得唯一的值作为 NumPy 数组返回。
```python
unique_values = series_from_list.unique()
```
通过掌握这些核心概念和技术细节,能够更高效地利用 `pandas.Series` 来完成各种数据分析任务。
pandas.core.series.Series创建一个该对象
创建一个 Pandas Series 对象,可以使用以下方式:
```python
import pandas as pd
# 从列表中创建Series
my_list = [10, 20, 30, 40]
s = pd.Series(my_list)
print(s)
# 从NumPy数组中创建Series
import numpy as np
my_array = np.array([10, 20, 30, 40])
s = pd.Series(my_array)
print(s)
# 从字典中创建Series
my_dict = {'a': 10, 'b': 20, 'c': 30, 'd': 40}
s = pd.Series(my_dict)
print(s)
```
这将创建一个包含指定数据的 Series 对象。Series 是一种一维标记数组,常用于处理时间序列数据、统计数据等。它由两个数组组成:索引数组和数据数组。索引数组包含数据标签,数据数组包含实际数据。Pandas Series 对象提供了许多有用的方法和属性,可以方便地对数据进行操作和分析。
阅读全文
相关推荐
















