我在大型熊猫数据室(1 500 000行(中重建句子有一个问题。我的目的是将单词用单词重建为新的数据框架,以便每行有一个句子。我的数据帧中有两个系列:单词&标签。每个句子都被感叹号分开。最重要的是,我想使用原始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为您快速回答。安迪的答案效果很好,尽管在创建新的数据框时,我需要进行一些修改。需要将单词称为字符串。
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)))
})
如果添加一个虚拟列为"名词",则可以使用普通的ol'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: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 = ''
让我知道您是否需要进一步的指示,我将很高兴提供帮助。