我试图从存储在 df 中的命名元组列表中提取第 n 个元素,如下所示:
df['text'] = [Tag(word='Come', pos='adj', lemma='Come'), Tag(word='on', pos='nounpl', lemma='on'), Tag(word='Feyenoord', pos='adj', lemma='Feyenoord')]
我试图只从每个元组中提取包含 pos 信息的元素。这是我想要达到的结果:
df['text'] = ['adj', 'nounpl', 'adj']
这是我到目前为止尝试过的:
d =[]
count = 0
while count < df['text'].size:
d.append([item[1] for item in df['text'][count]])
count += 1
dfpos = pd.DataFrame({'text':d})
df['text']= pd.DataFrame({'text':d})
df['text']=df['text'].apply(lambda x: ', '.join(x))
这是错误: IndexError: tuple index out of range
我错过了什么?
解决方案:似乎最简单的解决方案是将元组变成列表。我不确定这是否是最好的解决方案,但它有效。
d =[]
count = 0
while count < df['text'].size:
temp=([list(item[1:-1]) for item in df['text'][count]])
d.append(sum(temp, []))
count += 1
df['text']= pd.DataFrame({'text':d})
df['text2']=df['text'].apply(lambda x: ', '.join(x))
如果 Tag 是您的命名元组,请尝试使用 apply 进行索引
数据准备:
from collections import namedtuple
Tag = namedtuple('Tag', 'word pos lemma')
li = [Tag(word='Come', pos='adj', lemma='Come'), Tag(word='on', pos='nounpl', lemma='on'), Tag(word='Feyenoord', pos='adj', lemma='Feyenoord')]
df = pd.DataFrame({'text':li})
对于基于属性的选择.
在应用中使用,因为它是一个命名元组,即
df['new'] = df['text'].apply(lambda x : x.pos)
如果您需要基于索引的选择,请使用
df['new'] = df['text'].apply(lambda x : x[1] if len(x)>1 else np.nan)
输出 df['new']
0 adj 1 nounpl 2 adj 名称:文本,dtype:对象
另一种解决方案是str[1]
用于选择值namedtuple
:
df['text1'] = df['text'].str[1]
print (df)
text text1
0 (Come, adj, Come) adj
1 (on, nounpl, on) nounpl
2 (Feyenoord, adj, Feyenoord) adj
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句