【问题标题】:Extracting the n-th elements from a list of named tuples in pandas Python?从pandas Python中的命名元组列表中提取第n个元素?
【发布时间】:2018-04-17 15:38:03
【问题描述】:

我正在尝试从存储在 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?.
  • 标签是类还是命名元组?它是什么?怎么办? Nltk?
  • 标签是我使用 treetaggerwrapper 获得的命名元组。
  • 你能说出df['text'].apply(lambda x : x[1] if len(x) &gt; 1 else None).values的输出吗
  • 这也返回元组索引我们的范围错误

标签: python list pandas tuples


【解决方案1】:

如果 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 调整 1 名词 2 调整 名称:文本,数据类型:对象

另一种解决方案是使用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

【讨论】:

    猜你喜欢
    • 2011-03-19
    • 2020-09-29
    • 1970-01-01
    • 2018-02-07
    • 2013-04-29
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多