JesusMonroe
JesusMonroe

Reputation: 1601

Pandas - duplicating multiple rows with new values

I have a dataframe that looks like this:

  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

I have two dates that I need to add: 7/1/18 and 7/2/18. I need to copy all the entries for the last day of the previous month (6/29/18), only changing the date.

Output:

  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

The 7/1 and 7/2 dates have been added, using the same column values as 6/29.

(The output can be ordered by date as well, it doesn't matter).

Upvotes: 0

Views: 83

Answers (2)

yogkm
yogkm

Reputation: 649

Following method will return the updated dataframe for given dataframe, old_date and new_date

def change(df, old_date ,new_date):         
    temp_df = df.loc[old_date]
    temp_df.index = [new_date for _ in range(len(temp_df))]
    df=df.append(temp_df)
    return df

Upvotes: 1

Léopold Houdin
Léopold Houdin

Reputation: 1525

Suppose your original data frame is named df, then you could do:

# 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)

Upvotes: 1

Related Questions