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