【问题标题】:replacing each words in sentence into the words index using python使用python将句子中的每个单词替换为单词索引
【发布时间】:2020-04-16 02:24:41
【问题描述】:

我有两个 csv 文件,其中一个包含如下所示的句子:

                         sentences
0  yes good bye how should and bye
1                       bye should
2                         good bye

还有另一个 csv,其中包含每个单词及其旁边的索引,如下所示:

     word  frequency  index
0     and        500     10
1     you        334      1
2     how        320      2
3  should        250      3
4     yes        100      4
5     bye         50      5
6    good          1      6

我正在尝试使用 Dictionary 作为我的问题的解决方案,但它只打印一个单词而不是整个句子的奇怪输出

import string
import pandas as pd
text=pd.read_csv("one.csv")

change=pd.read_csv("result.csv")
print(text)
update = dict(zip(change.word, change.index))
print(update)
text1 = text['sentences'].replace(update, regex=True)
print(text1)
text1.to_csv('yes.csv', header=False, index=False)

我希望输出是:

4 6 5 2 3 10 5

5 3

6 5

我得到的是这个输出:

我在做什么错任何解决方案?

【问题讨论】:

    标签: python string pandas csv str-replace


    【解决方案1】:

    您可以在拆分每一行后对所有项目使用带有series.get 的列表推导:

    s=df2.set_index('word')['index']
    final=df1.assign(index=[[s.get(a) for a in i.split()] for i in df1['sentences']])
    

                             sentences                   index
    0  yes good bye how should and bye  [4, 6, 5, 2, 3, 10, 5]
    1                       bye should                  [5, 3]
    2                         good bye                  [6, 5]
    

    【讨论】:

    • 但这是打印句子以及如何让它只打印索引?
    • 它打印一个列表你还好吗?如果您希望它们作为字符串检查@ansev answer
    • 是的,我将列表转换回数据框以再次将其存储到 CSV 文件中,因为列表没有 to.csv 选项
    【解决方案2】:

    我们可以用一个系列来代替, 另一方面,关键似乎是使用Series.astype 将系列转换为str:

    text['index']=text.sentences.replace(change.set_index('word')['index']
                                               .astype(str),
                                         regex = True)
    print(text)
    #text.sentences.replace(change.set_index('word')['index'],regex = True)
    #0    10
    #1     3
    #2     5
    #Name: sentences, dtype: int64
    

    输出

                             sentences           index
    0  yes good bye how should and bye  4 6 5 2 3 10 5
    1                       bye should             5 3
    2                         good bye             6 5
    

    【讨论】:

    • 感谢您的回答,但您的正在将其转换为字符串,我会将这些数字输入神经网络,这可能会给我带来问题
    • 那么@anky_91 解决方案会做得很好:)。如果您想摆脱列表,我们可以建议使用爆炸。 final.explode('index')。虽然如果列表不是障碍,增加行数可能是错误的
    • 谢谢你的建议,我也会考虑爆炸
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2018-04-15
    • 2020-03-27
    • 1970-01-01
    相关资源
    最近更新 更多