要将列表 myList 转换为 Pandas 系列,请使用:
mySeries = pd.Series(myList)
这也是在 Pandas 中从列表创建系列的基本方法之一。
例子:
myList = ['string1', 'string2', 'string3']
mySeries = pd.Series(myList)
mySeries
# Out:
# 0 string1
# 1 string2
# 2 string3
# dtype: object
请注意,Pandas 会猜测列表元素的数据类型,因为系列不允许混合类型(与 Python 列表相反)。在上面的示例中,推断的数据类型是 object(Python string),因为它是最通用的并且可以容纳所有其他数据类型(请参阅 data types)。
创建系列时可以指定数据类型:
myList= [1, 2, 3]
# inferred data type is integer
pd.Series(myList).dtype
# Out:
# dtype('int64')
myList= ['1', 2, 3]
# data type is object
pd.Series(myList).dtype
# Out:
# dtype('O')
可以将dtype指定为整数:
myList= ['1', 2.2, '3']
mySeries = pd.Series(myList, dtype='int')
mySeries.dtype
# Out:
# dtype('int64')
但这只有在列表中的所有元素都可以转换为所需的数据类型时才有效。