熊猫-用新值复制多行

时间:2018-09-17 18:05:08

标签: python pandas dataframe

我有一个看起来像这样的数据框:

  date       code1    code2    code3
  6/1/18     X        Y        Z
  6/1/18     A        B        C
  6/1/18     S        D        F
  6/5/18     T        R        Y
  6/5/18     L        M        Q
  6/29/18    N        T        Z
  6/29/18    K        G        V
  6/29/18    B        A        C
  7/4/18     E        F        G

我需要添加两个日期:7/1/18和7/2/18。我需要复制上个月最后一天(18/29/29)的所有条目,仅更改日期。

输出:

  date       code1    code2    code3
  6/1/18     X        Y        Z
  6/1/18     A        B        C
  6/1/18     S        D        F
  6/5/18     T        R        Y
  6/5/18     L        M        Q
  6/29/18    N        T        Z
  6/29/18    K        G        V
  6/29/18    B        A        C
  7/4/18     E        F        G
  7/1/18     N        T        Z
  7/1/18     K        G        V
  7/1/18     B        A        C
  7/2/18     N        T        Z
  7/2/18     K        G        V
  7/2/18     B        A        C

使用与6/29相同的列值,添加了7/1和7/2日期。

(输出也可以按日期排序,没关系)。

2 个答案:

答案 0 :(得分:1)

假设原始数据框名为# Extract the rows you want df_tmp = df[df['date'] == '6/29/18'] # Update the date in the temporary dataframe df_tmp['date'] = '7/1/18' # Append your result to your original dataframe df = df.append(df_tmp) ,则可以执行以下操作:

on

答案 1 :(得分:1)

以下方法将为给定的数据帧old_date和new_date返回更新的数据帧

  class Boxes:
      'boxes with assigned weight'

      def __init__(self, boxnr, weight):
          self.boxnr = boxnr
          self.weight = weight

  box1 = Boxes('box1', 40)
  box2 = Boxes('box2', 70)
  box3 = Boxes('box3', 110)

  def tot_weight(self, weight):
      if input in Boxes:
          total += Boxes[weight.self]
  return self.tot_weight

  print ('which box?')
  weight = input ()

  print('what is your next box?')
  weight = input ()

  print (tot_weight.self.weight())
相关问题