繁体   English   中英

将列表列表转换为数据框列

[英]convert a list of lists to a dataframe column

我有一个看起来像这样的列表:

mylist = [['I','have','an','apple'],['she','have','an','orange']]

并且我希望 mylist 中包含的每个列表都应该是数据框中的一行,并且数据框应如下所示:

          text
'I','have','an','apple'
'she','have','an','orange'

我试图转换它,但它显示了这样的结果:

 0        1      2       3
'I'    'have'   'an'  'apple'
'she'  'have'   'an'  'orange'

我该怎么做?

注意。 使用list作为变量,这将覆盖内置蟒

数据框构造函数

您可以在 DataFrame 构造函数中使用字典:

lst = [['I','have','an','apple'],['she','have','an','orange']]
df = pd.DataFrame({'name': lst})

输出:

                      name
0     [I, have, an, apple]
1  [she, have, an, orange]

系列构造函数

或者,使用您转换为框架的系列:

df = pd.Series(lst, name='text').to_frame()

手动重塑 DataFrame 构造函数的输入

或者手动将每个列表包装在一个子列表中以避免扩展到列:

lst = [['I','have','an','apple'],['she','have','an','orange']]
df = pd.DataFrame([[e] for e in lst])

这是仅使用pd.DataFrame执行此操作的超级简单方法 -

mylist = [['I','have','an','apple'],['she','have','an','orange']]

df = pd.DataFrame({'text':mylist})
print(df)
                      text
0     [I, have, an, apple]
1  [she, have, an, orange]

尝试agg

>>> df.agg(list, axis=1)
0       [I, have, an, apple]
1    [she, have, an, orange]
dtype: object
>>> 

到数据DataFrame

>>> df.agg(list, axis=1).to_frame('text')
                      text
0     [I, have, an, apple]
1  [she, have, an, orange]
>>> 

尝试:

lst = [['I','have','an','apple'],['she','have','an','orange']]
df = pd.Series(lst, name='text').apply(lambda x: ', '.join(f"'{a}'" for a in x)).to_frame()

输出:

                            text
0     'I', 'have', 'an', 'apple'
1  'she', 'have', 'an', 'orange'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM