簡體   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