代码之家  ›  专栏  ›  技术社区  ›  twhale

在测试数据帧内容的真值时,如何解决ValueError?蟒蛇

  •  0
  • twhale  · 技术社区  · 8 年前

    我有一个这样的数据框。

       done    sentence                        3_tags
    0  0       ['What', 'were', 'the', '...]   ['WP', 'VBD', 'DT']
    1  0       ['What', 'was', 'the', '...]    ['WP', 'VBD', 'DT']
    2  0       ['Why', 'did', 'John', '...]    ['WP', 'VBD', 'NN']
    ...
    

    对于每一行,我想检查列' 3\u标签 “”位于列表temp1中,如下所示:

    a = pd.read_csv('sentences.csv')
    temp1 = [ ['WP', 'VBD', 'DT'], ['WRB', 'JJ', 'VBZ'], ['WP', 'VBD', 'DT'] ]
    q = a['3_tags'] 
    q in temp1
    

    对于第0行的第一句话,' 3\u标签 “=['WP',VBD',DT”“]这是temp1中的,因此我预计上述结果为:

    True
    

    但是,我遇到了以下错误:

    ValueError:数组长度不同:1对3

    我怀疑q的数据类型存在一些问题:

    print(type(q))
    <class 'pandas.core.series.Series'>
    

    问题是q是一个系列,而temp1包含列表?我应该怎么做才能得到逻辑结果“True”?

    1 回复  |  直到 8 年前
        1
  •  1
  •   piRSquared    8 年前

    您希望这些列表是元组。
    然后使用 pd.Series.isin

    *temp1, = map(tuple, temp1)
    
    q = a['3_tags'].apply(tuple)
    
    q.isin(temp1)
    
    0     True
    1     True
    2    False
    Name: 3_tags, dtype: bool
    

    然而,似乎 '3_tags' 列由看起来像列表的字符串组成。在这种情况下,我们想用 ast.literal_eval

    from ast import literal_eval
    
    *temp1, = map(tuple, temp1)
    
    q = a['3_tags'].apply(lambda x: tuple(literal_eval(x)))
    
    q.isin(temp1)
    
    0     True
    1     True
    2    False
    Name: 3_tags, dtype: bool
    

    设置1

    a = pd.DataFrame({
        'done': [0, 0, 0],
        'sentence': list(map(str.split, ('What were the', 'What was the', 'Why did John'))),
        '3_tags': list(map(str.split, ('WP VBD DT', 'WP VBD DT', 'WP VBD NN')))
    }, columns='done sentence 3_tags'.split())
    
    temp1 = [['WP', 'VBD', 'DT'], ['WRB', 'JJ', 'VBZ'], ['WP', 'VBD', 'DT']]
    

    设置2

    a = pd.DataFrame({
        'done': [0, 0, 0],
        'sentence': list(map(str.split, ('What were the', 'What was the', 'Why did John'))),
        '3_tags': list(map(str, map(str.split, ('WP VBD DT', 'WP VBD DT', 'WP VBD NN'))))
    }, columns='done sentence 3_tags'.split())
    
    temp1 = [['WP', 'VBD', 'DT'], ['WRB', 'JJ', 'VBZ'], ['WP', 'VBD', 'DT']]