【问题标题】:Extract words from the text by index into a new column Pandas Python通过索引从文本中提取单词到新列 Pandas Python
【发布时间】:2022-07-07 19:53:59
【问题描述】:

我有数据框:

data = {'text': ['They say that all cats land on their feet, but this does not apply to my cat. He not only often falls, but also jumps badly. We have visited the veterinarian more than once with dislocated paws and damaged internal organs.',
                'Mom called dad, and when he came home, he took moms car and drove to the store'],
       'begin_end':[[128, 139],[20,31]]}
        
df = pd.DataFrame(data)

我想使用begin_end 列中的一个数组将text 列中的单词提取到一个新列中,例如text[128:139+1]。所以它会是:

    begin_end     new_col
0   [128, 139]  have visited
1   [20, 31]    when he came

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    你需要使用循环:

    df['new_col'] = [s[a:b+1] for s, (a,b) in zip(df['text'], df['begin_end'])]
    

    输出:

                                                    text   begin_end       new_col
    0  They say that all cats land on their feet, but...  [128, 139]  have visited
    1  Mom called dad, and when he came home, he took...    [20, 31]  when he came
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      相关资源
      最近更新 更多