简体   繁体   中英

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
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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM