Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

python - Swapping rows within the same pandas dataframe

I'm trying to swap the rows within the same DataFrame in pandas.

I've tried running

a = pd.DataFrame(data = [[1,2],[3,4]], index=range(2), columns = ['A', 'B'])
b, c = a.iloc[0], a.iloc[1]
a.iloc[0], a.iloc[1] = c, b

but I just end up with both the rows showing the values for the second row (3,4).

Even the variables b and c are now both assigned to 3 and 4 even though I did not assign them again. Am I doing something wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use a temporary varaible to store the value using .copy(), because you are changing the values while assigning them on chain i.e. Unless you use copy the data will be changed directly.

a = pd.DataFrame(data = [[1,2],[3,4]], index=range(2), columns = ['A', 'B'])
b, c = a.iloc[0], a.iloc[1]


temp = a.iloc[0].copy()
a.iloc[0] = c
a.iloc[1] = temp

Or you can directly use copy like

a = pd.DataFrame(data = [[1,2],[3,4]], index=range(2), columns = ['A', 'B'])
b, c = a.iloc[0].copy(), a.iloc[1].copy()
a.iloc[0],a.iloc[1] = c,b

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...