遍历pd数据帧以将整数更改为字符串

时间:2018-12-14 18:09:12

标签: python loops

这是一个非常基本的问题,但是以某种方式我的循环无法正常工作。我有一个两列的pandas数据框;路径和单词。一个神经网络以词来预测结果值,但是它仍然是整数。我编写了一个for循环,用单词替换了这些整数,但是df中没有任何变化。我的df:

path    word
0   f7f172c01bec6a3e9a36dcafdf9e02e7df3522e4.wav    21
1   c17c29e392c57a9243ed52175568b40c04912194.wav    21
2   eea9239d4986b1f7dbffdcce76e0fce6e5f38ca8.wav    21
3   4fec4b033ba19d1ac875c0c062fda2869dbece73.wav    21

我的循环:

for i in df['word']:
    if i == 0:
        i == "backward"
    elif i == 1:
        i == "bed"
    elif i == 2:
        i == "bird"
    elif i == 3:
        i == "cat"
    elif i == 4:
        i == "dog"
    elif i == 5:
        i == "down"
    elif i == 6:
        i == "eight"
    elif i == 7:
        i == "five"
    elif i == 8:
        i == "follow"
    elif i == 9:
        i == "forward"
    elif i == 10:
        i == "four"
    elif i == 11:
        i == "go"
    elif i == 12:
        i == "happy"
    elif i == 13:
        i == "house"
    elif i == 14:
        i == "learn"
    elif i == 15:
        i == "left"
    elif i == 16:
        i == "marvin"
    elif i == 17:
        i == "nine"
    elif i == 18:
        i == "no"
    elif i == 19:
        i == "off"
    elif i == 20:
        i == "on"
    elif i == 21:
        i == "one"
    elif i == 22:
        i == "right"
    elif i == 23:
        i == "seven"
    elif i == 24:
        i == "sheilla"
    elif i == 25:
        i == "six"
    elif i == 26:
        i == "stop"
    elif i == 27:
        i == "three"
    elif i == 28:
        i == "tree"
    elif i == 29:
        i == "two"
    elif i == 30:
        i == "up"
    elif i == 31:
        i == "visual"
    elif i == 32:
        i == "wow"
    elif i == 33:
        i == "yes"
    elif i == 34:
        i == "zero"

1 个答案:

答案 0 :(得分:2)

您可以使用pd.Series.map

#Add the rest of your mapping here (I just included a few)
mapping = {0: 'backward', 1: 'bed', 21: 'one', 22: 'right'}

df['word'] = df['word'].map(mapping)

返回:

                                           path word
0  f7f172c01bec6a3e9a36dcafdf9e02e7df3522e4.wav  one
1  c17c29e392c57a9243ed52175568b40c04912194.wav  one
2  eea9239d4986b1f7dbffdcce76e0fce6e5f38ca8.wav  one
3  4fec4b033ba19d1ac875c0c062fda2869dbece73.wav  one