【问题标题】:How to iterate a dataframe then return rows values in python?如何迭代数据框然后在python中返回行值?
【发布时间】:2018-01-17 21:23:11
【问题描述】:

我有一个这样的数据框,

import pandas as pd
d = {'col1': ["2004-02-26", "2004-02-27", "2004-03-01",
              "2004-03-02", "2004-03-03", "2004-03-04",
              "2004-03-05", "2004-03-08", "2004-03-09",
              "2004-03-10", "2004-03-11", "2004-03-12"],
     'col2': [-3, 4, 5, 3, -1, 11, 123, 43, -5, 3, -4, -7],
     'col3': [0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0,]}
df = pd.DataFrame(data=d)
print(df)

打印出来,

              col1  col2  col3
    0   2004-02-26    -3     0
    1   2004-02-27     4     1
    2   2004-03-01     5     0
    3   2004-03-02     3     0
    4   2004-03-03    -1     1
    5   2004-03-04    11     0
    6   2004-03-05   123     0
    7   2004-03-08    43     0
    8   2004-03-09    -5     0
    9   2004-03-10     3     1
    10  2004-03-11    -4     1
    11  2004-03-12    -7     0

您可以在df['col2'] 中看到,正值由几个负值分隔。我想将每组正值的首尾行选择到一个新的数据帧中。如果只有一个积极的行留在 nagetives 中间,我假设头部和尾部是相同的。

例如,

head_date  col2h  co3h    tail_date  col2t  col3t
2004-02-27     4     1     2004-03-02     3     0
2004-03-04    11     0     2004-03-08    43     0
2004-03-10     3     1     2004-03-10     3     1

我正在考虑选择第​​ (i) 行 col20 时的行,返回 i+1 行值,以及当第 (i) 行 col2 >0 和第 (i+1) 行 col2

我希望我清楚地描述了这个问题。真的希望有人可以帮助我。

【问题讨论】:

    标签: python pandas loops dataframe


    【解决方案1】:

    类似的东西

    df1 = df.loc[(df['col2'].shift() < 0) & (df['col2'] > 0)].copy()
    df1.rename(columns = {'col1': 'head_date', 'col2': 'col2h', 'col3': 'col3h'}, inplace = True)
    
    df2 = df.loc[(df['col2'].shift(-1) < 0) & (df['col2'] > 0)].copy()
    df2.rename(columns = {'col1': 'head_date', 'col2': 'col2t', 'col3': 'col3t'})
    
    new_df = pd.concat([df1.reset_index(drop = True), df2.reset_index(drop = True)], axis = 1)
    

    你得到

        head_date   col2h   col3h   head_date   col2t   col3t
    0   2004-02-27  4       1       2004-03-02  3       0
    1   2004-03-04  11      0       2004-03-08  43      0
    2   2004-03-10  3       1       2004-03-10  3       1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-12
      • 2018-01-12
      • 2022-01-09
      • 2017-03-18
      • 1970-01-01
      • 2023-01-31
      • 2021-02-17
      • 2023-03-17
      相关资源
      最近更新 更多