熊猫:如何从每行一个单词重建字符串

时间:2018-04-25 14:08:05

标签: python string pandas dataframe nlp

我在使用大型Pandas DataFrame(1 500 000行)重建句子时遇到了问题。我的目标是将单词中的句子重建为一个新的数据帧,以便每行有一个句子。我的DataFrame中有两个系列:单词&标签。每个句子都用感叹号分隔。除此之外,我想使用原始DataFrame中的标签为形容词和名词/动词创建两个单独的系列到新的DataFrame中。所以这就是我所拥有的:

>df

word    tag

bike    NOUN
winner  NOUN
!       PUNCTUATION
red     ADJECTIVE
car     NOUN
is      VERB
fast    ADJECTIVE
!       PUNCTUATION
...     ...

这就是我想要的

>df2

sent             nounverb     adj

bike winner      bike winner  None
red car is fast  car is       red fast
...

我一直无法为此找到解决方案,因为我是Python的初学者,我无法想出一个能为我做这个的for loop

编辑:

谢谢Andy& Jesús快速回答。 Andy的回答工作得很好,虽然在创建新的DataFrame时我需要稍作修改。需要将这些单词称为字符串。

df2 = pd.DataFrame({
          "sent": g.apply(lambda sdf: " ".join(sdf.word.astype(str))),
          "nounverb": g.apply(lambda sdf: " ".join(sdf[sdf.is_nounverb].word.astype(str))),
          "adj": g.apply(lambda sdf: " ".join(sdf[sdf.tag == "ADJECTIVE"].word.astype(str)))
  })

2 个答案:

答案 0 :(得分:4)

如果为is" nounverb"添加虚拟列。你可以使用普通的' GROUPBY:

In [11]: df["is_nounverb"] = (df.tag == "NOUN") | (df.tag == "VERB")

然后你可以算上你已经看到的!枚举句子:

In [12]: df["sentence"] = (df.word == "!").cumsum()

In [13]: df = df[df.word != "!"]

In [14]: df
Out[14]:
     word        tag  sentence  is_nounverb
0    bike       NOUN         0         True
1  winner       NOUN         0         True
3     red  ADJECTIVE         1        False
4     car       NOUN         1         True
5      is       VERB         1         True
6    fast  ADJECTIVE         1        False

并分组:

In [15]: g = df.groupby("sentence")

In [16]: g.apply(lambda sdf: " ".join(sdf.word))
Out[16]:
sentence
0        bike winner
1    red car is fast
dtype: object

In [17]: g.apply(lambda sdf: " ".join(sdf[sdf.is_nounverb].word))
Out[17]:
sentence
0    bike winner
1         car is
dtype: object

In [18]: g.apply(lambda sdf: " ".join(sdf[sdf.tag == "ADJECTIVE"].word))
Out[18]:
sentence
0
1    red fast
dtype: object

一起:

In [21]: df2 = pd.DataFrame({
              "sent": g.apply(lambda sdf: " ".join(sdf.word)),
              "nounverb": g.apply(lambda sdf: " ".join(sdf[sdf.is_nounverb].word)),
              "adj": g.apply(lambda sdf: " ".join(sdf[sdf.tag == "ADJECTIVE"].word))
      })

In [22]: df2
Out[22]:
               adj     nounverb             sent
sentence
0                   bike winner      bike winner
1         red fast       car is  red car is fast

答案 1 :(得分:0)

解决方案继续沿着数据框中的第一列运行并组合句子列表。例如,您可以使用循环条件来跳过标点符号。然后对于你要组装成句子的每个临时单词,你应该组装一个描述(假设你们两者之间有1:1的相关性)。

我提出了一个不完整功能的小例子,但它应该指向正确的方向。

a = ['bike', 'winner', '!', 'red', 'car', 'is', 'fast', '!']
b = ['noun', 'noun', 'punctuation', 'adjective', 'noun', 'verb', 'adjective', 'punctuation']

temp_word = ''
temp_nounverb = ''
temp_adjective = ''
for index,word in enumerate(a):
    if word is not '!':
        temp_word += word + ' '
        if b[index] is 'noun' or b[index] is 'verb':
            temp_nounverb += word + ' '
            temp_adjective += 'None'
        else:
            temp_nounverb += 'None'
            temp_adjective += word + ' '
    else:
        print(temp_word + ' - ' + temp_nounverb + ' - ' + temp_adjective)
        temp_word = ''
        temp_nounverb = ''
        temp_adjective = ''

如果您需要进一步的指示,请告诉我,我很乐意提供帮助。

相关问题