Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 662
Zac Avatar asked Oct 23 '17 13:10

Zac


People also ask

How do I interchange rows in pandas DataFrame?

Pandas DataFrame: transpose() function The transpose() function is used to transpose index and columns. Reflect the DataFrame over its main diagonal by writing rows as columns and vice-versa. If True, the underlying data is copied. Otherwise (default), no copy is made if possible.

Can I use ILOC and LOC together?

loc and iloc are interchangeable when labels are 0-based integers.

Can you change values in a DataFrame?

For a DataFrame a dict can specify that different values should be replaced in different columns. For example, {'a': 1, 'b': 'z'} looks for the value 1 in column 'a' and the value 'z' in column 'b' and replaces these values with whatever is specified in value .


1 Answers

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
like image 89
Bharath Avatar answered Oct 02 '22 19:10

Bharath