【问题标题】:How to access the value of every single row pandas dictionary如何访问每一行熊猫字典的值
【发布时间】:2020-01-18 12:12:34
【问题描述】:

我从数据集创建字典,现在我想访问字典的每一行。这本字典的每一行都包含 2 个名字,例如:Winner: Alex Loser: Leo。 我的问题是我不知道如何通过索引访问这 2 个名称。

我想要这样的东西:
第 1 行:获胜者:亚历克斯 失败者:狮子座 我想像这样访问该行: dictionary[x] -> 所以我可以获取该行,然后一旦我有了该行,我想像 a=raw[y] 和 b=raw[y+1 一样访问它]。然后我想打印 A 和 B。我想这样做是因为我必须从每一行中复制一个特定的玩家并将其保存到另一个字典中。

这是我为创建字典和访问它而编写的代码,但不能按我的意愿工作。

dicti= imd4.to_dict('index') // dicti  is the dictionary that I created and imd4 is the dataset containing the Winner and the Loser name
for x in dicti:
print (x,':')
for y in dicti[x]:
    a=dicti[x][y]
    b=dicti[x][y+1]    //I can't do this  but I would like to do it. So I can save the data base on their index 
    print (y,':',dicti[x][y])
    print('Test :' ,a)

Here you can see how the dataset is build 预先感谢您的帮助。

【问题讨论】:

  • 为什么要为此将 DataFrame 转换为字典? minimal reproducible example 在哪里? but doesn't work as I wantI can't do this 是什么意思?

标签: python pandas machine-learning


【解决方案1】:

让我们建立一个测试字典:

test_dictionary=[
     {'winner':'ross','loser:'chandler'},
     {'winner':'rachael','loser:'phoebe'},
     {'winner':'joey','loser:'monica'},
     {'winner':'gunther','loser:'chandler'}
]

我们可以轻松循环:

for contest in test_dictionary:
    print (contest)

我们可以使用 enumerate 函数添加行号:

for line_number, contect in test_dictionary:
    print (line_number,contest)

所以现在我们有了可以轻松访问下一个元素的行号 - 我们必须记住,虽然我们不想访问最后一个元素,因为在此之后我们无法打印比赛,所以我们循环到[-1] 元素:

for line_number, contect in test_dictionary[:-1]:
    print (line_number,contest)
    print (line_number+1,test_dictionary[line_number+1])

我们也可以简单地使用 test_dictionary 的长度范围并直接访问元素:

for line_number in range(len(test_dictionary)-1]:
    print (line_number,test_dictionary[line_number])
    print (line_number+1,test_dictionary[line_number+1])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多