【问题标题】:Pandas loop through dataframe and list with while loopPandas 循环遍历数据框并使用 while 循环列出
【发布时间】:2018-05-30 04:48:11
【问题描述】:

我正在尝试遍历列表和数据框,如果列表中的 id 等于数据框中的 id,则对数据框中的该行执行某些操作。

import pandas as pd
data = [['a1','Alex',10],['a1','Bob',12],['a1','Clarke',13],['a2','den',14],['a2','emry',15]]
df = pd.DataFrame(data,columns=['id','Name','Age'])

unique_ids = ['a1','a2']

首先循环遍历列表。如果数据框中的 id == unique_ids 列表中的 id,则执行以下操作:

  • 如果下一行中的唯一 ID 仍与前一行相同,则将第二个参数设置为上一行的最后一个值。因此,由于12 是第一行的最后一项,a1 仍然是与上面相同的 id,因此将 12 设置为第二行的第二个值。

例如:上述输入的预期输出为

a1,10,12 
a1,12,13 
a2,14,15

我是如何做到的:

for i in unique_ids:
    for row in df.itertuples(index=True, name='Pandas'):
        while i == getattr(row,"id"):
           print (getattr(row,"id"),getattr(row,"age")
           not sure how to proceed as im getting stuck at the while loop

【问题讨论】:

    标签: python pandas while-loop


    【解决方案1】:

    我认为你想做的事情可以通过跟踪最后一行的 id 来完成。

    import pandas as pd
    data = [['a1','Alex',10],['a1','Bob',12],['a1','Clarke',13],['a2','den',14],['a2','emry',15]]
    df = pd.DataFrame(data,columns=['id','Name','Age'])
    
    unique_ids = ['a1','a2']
    last_id = df.iloc[0]['id']  # initilize to the first row's id
    for idx, row in df[1:].iterrows():  
        if row['id'] in unique_ids and row['id'] == last_id:
            # You can retrieve last row by df.iloc[idx-1]
            print(row['id'], ",", df.iloc[idx-1]['Age'], ",", row['Age']) 
        last_id = row['id'] # update last_id
    
    Output:
    a1 , 10 , 12
    a1 , 12 , 13
    a2 , 14 , 15
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 2019-08-13
      • 2021-08-20
      • 1970-01-01
      相关资源
      最近更新 更多