【问题标题】:To merge excel tables with some equals names of columns with python and pandas使用 python 和 pandas 合并具有某些列名的 excel 表
【发布时间】:2020-08-10 04:15:54
【问题描述】:

有两个excel表:

表1:

id  name    color   size
1   shoes   black   42
2   shoes   black   44
3   jacket  brown   44
4   jacket  brown   46

表2:

name    size    country            host     id
shoes   42      usa      cotton    man  
shoes   44      rus                woman    2
jacket  44      eu                 man  
shoes   46      usa      polieste  woman    
shoes   42      rus                man  
hat     m       eu                 woman

需要制作table3,插入一些等于列的数据,例如(namesize)或只是(id)而不包括带有未命名列的列

像这样(对于等于 namesize):

name    size    country host    id  color
shoes   42      usa     man     1   black
shoes   44      rus     woman   2   black
jacket  44      eu      man     3   brown
shoes   46      usa     woman       
shoes   48      rus     man     
hat     m       eu      woman   

是否可以在带有 DataFrame 的 pandas 中使用?

【问题讨论】:

标签: python excel pandas dataframe merge


【解决方案1】:

首先您需要将size 列从table1 转换为str,因为table2 中的size 也是一个字符串列:

In [40]: table1['size'] = table1['size'].astype(str)

然后,你可以像这样加入他们:

In [44]: table3 = pd.merge(table2, table1, on=['name', 'size'], how='left').drop(['Unnamed: 3', 'id_x'], 1).rename(columns={'id_y': 'id'})                                                                  

In [45]: table3                                                                                                                                                                                             
Out[45]: 
     name size country   host   id  color
0   shoes   42     usa    man  1.0  black
1   shoes   44     rus  woman  2.0  black
2  jacket   44      eu    man  3.0  brown
3   shoes   46     usa  woman  NaN    NaN
4   shoes   42     rus    man  1.0  black
5     hat    m      eu  woman  NaN    NaN

【讨论】:

    猜你喜欢
    • 2013-08-01
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 2016-02-12
    相关资源
    最近更新 更多