user3735871
user3735871

Reputation: 317

Pandas dataframe how to drop and rename column

For a data frame as below, I am trying to 1) Drop column B, as it is not in the rows values of Marker, 2) then rename Column A, C, D to new names ColA, ColB, ColC according to the Values under Column New_Name. What could be a way to do this? Do I need to put column New_Name into a list and iterate through the Dataframe column names soemhow? Many thanks for your help.

          A     B     C      D        Marker   New_Name
         1.0   0.0   0.0    1.0        A          ColA
         1.0   0.0   0.0    0.0        C          ColC
         0.0   0.0   0.0    0.0        D          ColD

Upvotes: 3

Views: 8098

Answers (3)

BENY
BENY

Reputation: 323326

s=df.reindex(columns=df.Marker).\
    rename(columns=dict(zip(df.Marker,df.New_Name))).\
     rename_axis(None,axis=1)
s
   ColA  ColC  ColD
0   1.0   0.0   1.0
1   1.0   0.0   0.0
2   0.0   0.0   0.0

Upvotes: 2

Albin johnson
Albin johnson

Reputation: 21

Rename the columns using a mapping and df.rename():

df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
df.rename(columns={"A": "a", "B": "c"})

print(df):

   a    c
0  1  4
1  2  5
2  3  6

Upvotes: 2

wwnde
wwnde

Reputation: 26676

Can keep Marker names as row names thus;

df2=df.drop(columns=['Marker','B']).set_index('New_Name').T.rename_axis('Marker',axis=1)
df2

Upvotes: 1

Related Questions