栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

熊猫的DataFrame-重命名多个相同名称的列

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

熊猫的DataFrame-重命名多个相同名称的列

我希望在Pandas中找到比通用Python解决方案更多的解决方案。如果Column的get_loc()函数找到带有“
True”值的重复项,则该掩码数组将返回掩码数组,“
True”值指向找到重复项的位置。然后,我使用掩码将新值分配到这些位置。在我的情况下,我提前知道我要获得多少个dups,以及我将分配给他们什么,但是看起来df.columns.get_duplicates()将返回所有dups的列表,然后您就可以如果您需要更通用的重复除草操作,请将该列表与get_loc()结合使用

’‘’更新至2020年9月’‘’

cols=pd.Series(df.columns)for dup in df.columns[df.columns.duplicated(keep=False)]:     cols[df.columns.get_loc(dup)] = ([dup + '.' + str(d_idx)     if d_idx != 0     else dup     for d_idx in range(df.columns.get_loc(dup).sum())]   )df.columns=cols    blah    blah2   blah3   blah.1  blah.2 0     0        1       2        3       4 1     5        6       7        8       9

更好的新方法(更新03Dec2019)

下面的这段代码比上面的代码更好。从下面的另一个答案(@SatishSK)复制:

#sample df with duplicate blah columndf=pd.Dataframe(np.arange(2*5).reshape(2,5))df.columns=['blah','blah2','blah3','blah','blah']df# you just need the following 4 lines to rename duplicates# df is the dataframe that you want to rename duplicated columnscols=pd.Series(df.columns)for dup in cols[cols.duplicated()].unique():     cols[cols[cols == dup].index.values.tolist()] = [dup + '.' + str(i) if i != 0 else dup for i in range(sum(cols == dup))]# rename the columns with the cols list.df.columns=colsdf

输出:

    blah    blah2   blah3   blah.1  blah.20   0   1   2   3   41   5   6   7   8   9


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/624148.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号