簡體   English   中英

如何在重寫熊貓數據框中的潛在重復項時重命名列

[英]How to rename columns while overwriting potential duplicates in pandas dataframe

我有一個pandas.dataframe

import pandas as pd
df = pd.DataFrame( {'one': pd.Series([1., 2., 3.], 
                                     index=['a', 'b', 'c']),
                    'two': pd.Series([1., 2., 3., 4.], 
                                     index=['a', 'b', 'c', 'd']),
                    'three': pd.Series([0., 6., 1.], 
                                     index=['b', 'c', 'd']),
                    'two_': pd.Series([1., 2., 5, 4.], 
                                     index=['a', 'b', 'c', 'd'])})

要么

print (df) 
#   one  three  two  two_
#a    1    NaN    1     1
#b    2      0    2     2
#c    3      6    3     5
#d  NaN      1    4     4

我有一張地圖,將某些列重命名為

name_map = {'one': 'one', 'two': 'two_'} 
df.rename(columns=name_map)
#    one  three  two_  two_
# a    1    NaN     1     1
# b    2      0     2     2
# c    3      6     3     5
# d  NaN      1     4     4

(有時name_map可能會將一列映射到自身,例如'one'->'one')。 我到底想要的是對象

#    one_  three  two_ 
#a     1    NaN      1    
#b     2      0      2    
#c     3      6      3    
#d   NaN      1      4        

重命名之前,我應該如何刪除潛在的重復項?

首先獲取公用列list(set(name_map.values()) & set(df.columns))drop() 並且,然后使用columns=name_map rename()rename()

In [16]: (df.drop(list(set(name_map.values()) & set(df.columns)), axis=1)
            .rename(columns=name_map))
Out[16]:
   one_  two_
a     1     1
b     2     2
c     3     3
d   NaN     4

我有一種方法,但似乎有點混亂(處理NaN值會導致混亂)

potential_duplicates = [ new 
                         for old,new in name_map.items() 
                         if new in list(df) # if the new column name exists
                         and 
                         pd.np.any( df[old][df[old]==df[old]]  # if said column differs from the one to be renames 
                                     != df[new][df[new]==df[new]] ) ]

df.drop( potential_duplicates, axis = 1, inplace=True)

df.rename( columns=name_map) 

#    one_  two_ 
#a     1     1
#b     2     2
#c     3     3
#d   NaN     4

我認為最簡單的方法是刪除name_map值列表中不存在的列(因為您要刪除前two列)

In [74]: df
Out[74]: 
   one  two  two_
a    1    1     1
b    2    2     2
c    3    3     5
d  NaN    4     4

In [76]: df.drop([col for col in df.columns if col not in name_map.keys()], axis=1)
Out[76]: 
   one  two
a    1    1
b    2    2
c    3    3
d  NaN    4

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM