【问题标题】:Looping over dataframe with extracting different columns at each iteration在每次迭代中提取不同的列来循环数据帧
【发布时间】:2020-11-27 16:17:11
【问题描述】:

我正在尝试遍历数据框 df,并且我想在每次迭代时提取不同的列。

假设我的 df 中有列:['A', 'B', 'C', 'D', 'E', 'F']

column_names=[['A','B'],['A','C','D']]

    for index,row in df:  //lets assume index starts with 0
       row[column_names[index]] // However you can not apply this syntax for rows like you could for a df to get a sub dataframe. 

我有哪些选择?我尝试过 itertuples 和 iterrows,但您不能通过传递列名列表来选择不同的列

谢谢

【问题讨论】:

  • 请分享数据框的示例输入和预期输出,以便更好地理解。
  • 也可以澄清一下——你想循环,做什么?就像你说的 - 这种方法不适用于循环,但适用于数据帧,可能你可以在这里利用矢量化处理......

标签: python dataframe iteration


【解决方案1】:

遍历列和检索数据帧的最简单方法是反转循环:

for col in column_names:
    for ix in df.index:
        print(df.loc[ix, col])

【讨论】:

    【解决方案2】:

    使用iterrows(),您将获得一个元组,其索引位于第 0 位,行位于第 1 位。您可能希望将iterrows() 用作:

    column_names=[['A',"B"],['A','C','D']]
    for row in df.iterrows():
        print(row[1][column_names[row[0]]].to_frame())
    

    对于一个 df 即:

        A   B   C   D   E   F
    0   1.0 1.0 1.0 1.0 1.0 1.0
    1   1.0 1.0 1.0 1.0 1.0 1.0
    

    你得到:

    A    1.0
    B    1.0
    Name: 0, dtype: float64
    A    1.0
    C    1.0
    D    1.0
    Name: 1, dtype: float64
    

    【讨论】:

    • 谢谢这让我更接近了。 row[1][column_names[0] 是一个系列。我必须将其转换回 DataFrame(我知道带有一个条目的数据帧没有意义)并使用 .T 将其转回原始格式。我想我需要改变我的逻辑。谢谢
    • 你也可以这样做!更新了我的答案以包括使用.to_frame()
    猜你喜欢
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多