将list或numpy array或dict转为pd.Series。 python
时间: 2024-03-01 17:49:40 浏览: 19
你可以使用 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
```
相关问题
python将list中的numpy.array存到本地.png文件
在Python中,我们可以使用PIL(Python Imaging Library)库来将list中的numpy.array存到本地.png文件。以下是具体步骤:
1. 首先,导入需要的库:
from PIL import Image
import numpy as np
2. 将list中的numpy.array转化为图片格式,可以先将其转化为numpy.array类型再使用Image.fromarray()函数转化为图片格式。例如:
arr_list = [np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint8),
np.array([[10, 20, 30], [40, 50, 60]], dtype=np.uint8)]
for i, arr in enumerate(arr_list):
im = Image.fromarray(arr)
3. 将图片存储到本地.png文件,可以使用Image.save()函数。例如:
im.save(f'array_{i}.png')
完整的代码实现如下:
from PIL import Image
import numpy as np
arr_list = [np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint8),
np.array([[10, 20, 30], [40, 50, 60]], dtype=np.uint8)]
for i, arr in enumerate(arr_list):
im = Image.fromarray(arr)
im.save(f'array_{i}.png')
这样就成功将list中的numpy.array存到本地.png文件了。
如果将一个numpy.array型的图像转为torch.tensor型
的图像,应该怎么做?
可以使用torch.from_numpy()函数将numpy.array型的图像转为torch.tensor型的图像。具体代码如下:
import torch
import numpy as np
# 假设img是一个numpy.array型的图像
img = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# 将img转为torch.tensor型的图像
img_tensor = torch.from_numpy(img)
print(img_tensor)
输出结果为:
tensor([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]], dtype=torch.int32)