簡體   English   中英

熊貓數據框中行的列表列表

[英]List of lists to rows in a pandas dataframe

使用腳本后,我的算法將受保護的結果返回到類似以下列表的列表中: pred=[[b,c,d],[b,a,u],...[b,i,o]]

我已經有一個數據框,需要將這些值添加到新的匹配列中。 列表與框架中的其他列一樣,正好是x長,我只需要使用列表的所有值創建一個新列。

但是,當我嘗試將列表放入列中時,出現錯誤:

ValueError: Length of values does not match length of index

查看數據,它將整個列表放到一行中,而不是將每個條目放到新行中。

編輯:

列表中的所有值都應放在列namend pred

sent  token   pred
 0     a        b
 0     b        c
 0     b        d
 1     a        b
 1     b        a
 1     c        u

解:

x = []
for _ in pred:
  if _ is not None:
    x += _

df_new = pd.DataFrame(df)
df_new["pred"] = list(itertools.chain.from_iterable(x))
import pandas as pd

# combine input lists
x = []
for _ in [['b','c','d'],['b','a','u'], ['b','i','o']]:
    x += _

# output into a single column
a = pd.Series(x)

# mock original dataframe
b = pd.DataFrame({'sent': [0, 0, 0, 1, 1, 1], 
                  'token': ['a', 'b', 'b', 'a', 'b', 'c']})

# add column to existing dataframe
# this will avoid the mis matched length error by ignoring anything longer 
# than your original data frame
b['pred'] = a

   sent token pred
0     0     a    b
1     0     b    c
2     0     b    d
3     1     a    b
4     1     b    a
5     1     c    u

您可以使用itertools.chain ,它可以展平列表列表,然后可以根據數據幀的長度對其進行切片。

來自@ak_slick的數據。

import pandas as pd
from itertools import chain

df = pd.DataFrame({'sent': [0, 0, 0, 1, 1, 1], 
                   'token': ['a', 'b', 'b', 'a', 'b', 'c']})

lst = [['b','c',None],['b',None,'u'], ['b','i','o']]

df['pred'] = list(filter(None, chain.from_iterable(lst)))[:len(df.index)]

print(df)

   sent token pred
0     0     a    b
1     0     b    c
2     0     b    d
3     1     a    b
4     1     b    a
5     1     c    u

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM