Toggle rows and indexes in the panas

Asked 2 years ago, Updated 2 years ago, 46 views

This is a question about Pandas' DataFrame.
Is it possible to substitute the specified line for the index?

e.g.)

index AB
    1   1.0 2.0
    2   3.0 4.0 
2 Operation to substitute the second line
index 3.0 4.0
    1   1.0 2.0

python pandas

2022-09-30 17:22

3 Answers

I think you can describe how to make the element of a specified line a column name.

import pandas as pd
df = pd.DataFrame ([1.0, 2.0], [3.0, 4.0]], columns = ['A', 'B'])

df.rename (columns=df.iloc[1], replace=True)
print(df)
# = > 3.0 4.0
#    0  1.0  2.0
#    1  3.0  4.0

Furthermore, if you don't need the second row (index=1),

df.drop(1,inplace=True)

Please.


2022-09-30 17:22

It is true that the meaning of the problem is ambiguous, but is it like this?

df=pd.DataFrame([1.0, 2.0], [3.0, 4.0]], index=range(1,3), columns=["A", "B"])
df

>AB
> 11.0 2.0
>23.0 4.0

df.loc[1,:] = df.loc[2,:]
df

>AB
>13.0 4.0
>23.0 4.0


2022-09-30 17:22

import pandas as pd

df=pd.DataFrame([1.0, 2.0], [3.0, 4.0]], index=range(1,3), columns=["A", "B"])
print(df)

print('---')

df2 = df.T.set_index(2).T
print(df2)

print(df2.shape)

Do the above to:

AB
1  1.0  2.0
2  3.0  4.0
---
2  3.0  4.0
1  1.0  2.0
(1, 2)


2022-09-30 17:22

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.