根据不同数据帧中的条件从数据帧中读取日期

时间:2018-06-01 04:40:19

标签: python pandas

我有2个数据框。 我需要根据另一个

的值从一个数据框中读取值

词:

words = pd.DataFrame()
words['no'] = [1,2,3,4,5,6,7,8,9]
words['word'] = ['cat', 'in', 'hat', 'the', 'dog', 'in', 'love', '!', '<3']
words

句:

sentences =  pd.DataFrame()
sentences['no'] =[1,2,3]
sentences['start'] = [1, 4, 6]
sentences['stop'] = [3, 5, 9]
sentences

所需的输出是文本文件:

cat in hat
***
the dog
***
in love ! <3

但是我无法通过这一步,我尝试运行以下代码:

for x in sentances:     打印(单词[&#39;单词&#39;] [单词[&#39; no&#39;]。(句子[&#39;开始&#39;],句子[&#39;停止&#39;] ],包含=真)

但是我发现了这个错误

 File "<ipython-input-16-ae3f5333be66>", line 3
    print(words['word'][words['no'].between(sentences['start'], sentences['stop'], inclusive = True)
                                                                                                    ^
SyntaxError: unexpected EOF while parsing

2 个答案:

答案 0 :(得分:2)

no设置为words的索引,然后使用列表解析迭代sentences

v = words.set_index('no')['word']
sentences = [
    ' '.join(v.loc[i:j]) for i, j in zip(sentences['start'], sentences['stop'])
]

或索引不可知:

v = words['word'].tolist()
sentences = [
    ' '.join(v[i - 1:j - 1] for i, j in zip(sentences['start'], sentences['stop'])
]

['cat in hat', 'the dog', 'in love ! <3']

从这里保存到文件应该很简单:

with open('file.txt', 'w') as f:
    for sent in sentences:
        f.write(sent + '\n')
        f.write('***\n')

答案 1 :(得分:1)

解决这个问题的一种方法,

res=pd.DataFrame()
res['s']=sentences.apply(lambda x: ' '.join(words.iloc[(x['start']-1):(x['stop'])]['word']),axis=1)
res.to_csv('a.txt',index=False,header=False,line_terminator='\n***\n')