Search code examples
pythonpandascopy-paste

Excel Copy Paste Way in Python


I have a data frame as below

df = pd.DataFrame([[3,2,1],[4,5,6],[10,20,30]], columns = ['A','B','C'])

    A   B   C
0   3   2   1
1   4   5   6
2  10  20  30

Is there any way in python to mimic copy and paste function in excel? For example I want to copy paste row 0 column A and B and paste them into row 0 column B and C, such that it will become

    A   B   C
0   3   3   2
1   4   5   6
2  10  20  30

In a small data frame, I can use:

df.loc[0,'C'] = df.loc[0,'B']
df.loc[0,'B'] = df.loc[0,'A']

But my original data frame is sizable and I prefer not to do this one element by one element. I was also trying to do:

df.loc[0,['A','B']] = df.loc[0,['B','C']]

But my data in row 0 column A becomes NaN.

So is there a way of doing things similar like doing copy paste in excel in python (simply block a range of data, copy them and paste them on top of another existing data)? Thanks


Solution

  • anky_91's answer

    df.loc[0, ['B', 'C']] = df.loc[0, ['A', 'B']].to_numpy()
    

    shift

    There are many ways you can use shift. This is just one.

    df.update(df.shift(axis=1)[['B', 'C']])
    

    For reasons that I'm not happy about, you can provide a fill_value to shift to preserve the integer dtype

    df.update(df.shift(axis=1, fill_value=0)[['B', 'C']])