1

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

3
  • The columns name do matter when you assign the value , so adding .values or to_numpy() to remove the impact of index Commented Nov 5, 2019 at 15:35
  • I did this, but like I mentioned above: I have a large data set, so I want the code to block certain range of row and paste it on top of another range of existing row. Thanks. Commented Nov 5, 2019 at 15:35
  • 1
    @anky_91 if you post an answer, let me know and I'll edit my post accordingly. Commented Nov 5, 2019 at 16:02

2 Answers 2

2

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']])
Sign up to request clarification or add additional context in comments.

Comments

0

This mostly feels like a bad idea, but if it's what you really want to do, you can use .iloc to address columns by number and just shift them:

In [56]: df.iloc[0, 1:] = df.iloc[0, :-1].values

In [57]: df
Out[57]:
    A   B   C
0   3   3   2
1   4   5   6
2  10  20  30

2 Comments

Hi Randy, is there any possibility to take a range of columns by their names instead of number? Thanks.
Yes, as noted in anky_91's comment, you can just flip your assignment around with .loc and use .values/.to_numpy() if you want to assign them by name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.