繁体   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