【问题标题】:Looping by row, and then by column using pandas按行循环,然后使用熊猫按列循环
【发布时间】:2019-04-08 22:50:31
【问题描述】:

我需要按行(在一列内)循环,然后按数据集中的其余列循环。

我已经尝试过使用 iterows()、iloc() 和 iat()。

import pandas as pd

# Two-dimensional data frame
table = {'A' : [0.1, -0.2, 0.3, -0.4],'B' : [-0.2, 0.4, 0.6, 0.8], 'C' : [0.3, -0.6, -0.9, -1.3]}

# Setting index to be new column
df = pd.DataFrame(table, index = ['W','X','Y','Z'])

column_list = list(df.columns)
total_columns = len(column_list)

total_rows = len(df.index)

column_num = 1
column = column_list[column_num]


winners = []
losers = []
zero = []   


for col_num in df: 
    row_num = 1
    for row_num in df:
        if (df.iloc[row_num][column]) > 0:
            winners.append(df.iloc[row_num][column])

        elif (df.iloc[row_num][column]) < 0:
            losers.append(df.iloc[row_num][column])

        else:
            zero.append(df.iloc[row_num][column])

        row_num = row_num + 1

【问题讨论】:

  • 预期结果是什么?
  • 如果我没看错,您只想从数据帧的所有元素中创建一个列表,从第一个索引 fir 元素开始,到最后一个索引 last 元素正确吗?跨度>
  • 我想在列中逐行迭代,然后重复列数。
  • 每一列的结果将成为另一个数据框中的条目

标签: python pandas loops rows


【解决方案1】:

您可以使用 iterrows,并在列表推导中执行此操作。

In [11]: [x for _, col in df.iteritems() for x in col]
Out[11]: [0.1, 0.2, 0.3, 0.4, 0.2, 0.4, 0.6, 0.8, 0.3, 0.6, 0.9, 1.3]

或者你可以展平 numpy 数组:

In [12]: list(df.values.T.flatten())
Out[12]: [0.1, 0.2, 0.3, 0.4, 0.2, 0.4, 0.6, 0.8, 0.3, 0.6, 0.9, 1.3]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 2021-06-30
    • 1970-01-01
    相关资源
    最近更新 更多