【问题标题】:How (with apply) to select and copy specific columns in a Dataframe according to index or another column如何(通过应用)根据索引或另一列选择和复制数据框中的特定列
【发布时间】:2017-09-19 13:41:25
【问题描述】:

我已经问过我的问题,但它的描述不够准确。 这个论坛的聪明人已经提出了解决方案,但我忘了(抱歉)如果相关列中有零,应该保留。

您好,我有一个如下所示的数据框

              2014  2015  2016  2017  2018  2019  

         2014   10    20    30    40    0      5
         2015   0     0    200    0    100     0       
         2016   0     0    200   140    35    10       
         2017   0     0     0     20     0    12       

我需要这样的结果:

    yearStart  yearStart+1  yearStart+2  yearStart+3  yearStart+4  
0      10          20            30          40          0
1      0          200             0          100         0       
2     200         140            35          10          0
3      20          0             12           0          0

想法是在每一行中选择两个日期之间的列:

index 和 index +delta,使用 delta 参数(在本例中为 4)将它们放入数据帧中。

使用 iterrows() 会花费太多时间。

我试过了

 df1 = df.apply(lambda x: pd.Series(x[x.keys()>=x.index],1)).fillna(0).astype(int)

但它不起作用:

TypeError: ('Index(...) must be called with a collection of some kind,
1 was passed', 'occurred at index 2014')

谢谢

【问题讨论】:

标签: python python-3.x pandas apply


【解决方案1】:

其中一种方法是

In [1010]: def yearmove(x):
      ...:     idx = x.index.astype(int)
      ...:     idx = idx - x.name
      ...:     mask = idx >= 0
      ...:     idx = 'yearStart' + idx.astype(str)
      ...:     return pd.Series(x.values[mask], index=idx[mask])
      ...:

In [1011]: df.apply(yearmove, 1).fillna(0).astype(int)
Out[1011]:
      yearStart0  yearStart1  yearStart2  yearStart3  yearStart4  yearStart5
2014          10          20          30          40           0           5
2015           0         200           0         100           0           0
2016         200         140          35          10           0           0
2017          20           0          12           0           0           0

【讨论】:

  • 谢谢。它完美地工作。如果我需要对时间窗口持续时间有条件,我会写 mask=(idx>=0 和 idx
  • 我意识到我的错误:'and' 而不是 '&' 但是使用 '&' 运算符在 'int' 和 'int64' 之间存在类型错误...我正在跟踪它跨度>
猜你喜欢
  • 2014-05-23
  • 2020-10-03
  • 2018-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-18
相关资源
最近更新 更多