【问题标题】:How to access (i+1 ) index in the second for loop in the below case?在以下情况下,如何在第二个 for 循环中访问 (i+1 ) 索引?
【发布时间】:2021-05-14 01:32:07
【问题描述】:

火车是一个数据框,其中有两列:

  Address   gender
0 abc        f
1 dfg        m
2 hjk        m
3 ert        m

当性别相同时,我需要对地址列执行一些操作,因此我正在使用此代码,而且我是 python 和 pandas 的新手,所以我不知道我是否正确有效地执行此操作。


for i in train.index:
    for j in train.index[i+1]:
        
        if train.loc[i,'gender']== train.loc[j,'gender']:
            print(train['Address'])

目前,此代码报错:

'int' object is not iterable

谁能帮我解决这个问题?

【问题讨论】:

  • 分享完整代码。
  • 哪一行是错误
  • 第二个循环线
  • 你不应该像这样开始使用熊猫。
  • 那我应该怎么用你能帮我吗?

标签: python pandas


【解决方案1】:

您遇到的错误是因为 train.index[i+1] 不可交互。它是一个整数。

为什么不使用.shift 而使用第二个循环?

for i in train.index:
    if train.loc[i,'gender']== train['gender'].shift(-1)[i]:
        print(train['Address'])

请记住,print(train['Address']) 行将打印所有 'Address' 列。如果您在条件为True 时想要特定的'Address',则应使用print(train['Address'][i])

【讨论】:

    猜你喜欢
    • 2021-09-21
    • 2019-10-29
    • 2017-07-18
    • 2021-11-24
    • 2021-09-19
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 2019-07-02
    相关资源
    最近更新 更多