什么方法可以将Python字符串列表转换为
(pandas Series对象可以使用
pd.Series
对象?(pandas Series对象可以使用
tolist()
方法转换为列表,但如何进行反向转换?)我理解你的列表实际上是一个嵌套的列表
import pandas as pd
thelist = [ ['sentence 1'], ['sentence 2'], ['sentence 3'] ]
df = pd.Series( (v[0] for v in thelist) )
要将列表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
),因为它是最通用的并且可以容纳所有其他数据类型(请参见数据类型)。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')
但是,只有当列表中的所有元素都可以转换为所需的数据类型时,这才有效。
import pandas as pd
sentence_list = ['sentence 1', 'sentence 2', 'sentence 3', 'sentence 4']
print("List of Sentences: \n", sentence_list)
sentence_series = pd.Series(sentence_list)
print("Series of Sentences: \n", sentence_series)
即使sentence_list是一个列表,这段代码仍将列表转换为Pandas Series对象。
pd.Series(l)
实际上适用于几乎任何类型的列表,并返回 Series 对象:
最初的回答
import pandas as pd
l = [ ['sentence 1'], ['sentence 2'], ['sentence 3'] ] #works
l = ['sentence 1', 'sentence 2', 'sentence 3'] #works
l = numpy.array(['sentance 1', 'sentance2', 'sentance3'], dtype='object') #works
print(l, type(l))
ds = pd.Series(l)
print(ds, type(ds))
0 sentence 1
1 sentence 2
2 sentence 3
dtype: object <class 'pandas.core.series.Series'>