要将列表myList转换为熊猫系列,请使用:mySeries = pd.Series(myList)
这也是从熊猫的列表中创建系列的基本方法之一。
示例: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')
但是,只有当列表中的所有元素都可以强制转换为所需的数据类型时,这才有效。