python - 需要处理具有非唯一多索引的串联数据帧

标签 python python-3.x pandas dataframe

这个有效:

import pandas as pd

raw_data = {
        'type_1': [1, 1],
        'id_1': ['2', '3'],
        'name_1': ['Alex', 'Amy']}
df_a = pd.DataFrame(raw_data, columns = ['type_1', 'id_1', 'name_1'])

raw_datab = {
        'type_2': [1, 1],
        'id_2': ['4', '5'],
        'name_2': ['Billy', 'Brian']}
    df_b = pd.DataFrame(raw_datab, columns = ['type_2', 'id_2', 'name_2'])

    dfs = [df_a.set_index(['type_1','id_1']),
           df_b.set_index(['type_2','id_2'])]

    df = pd.concat(dfs, axis=1)
    print (df)

打印:

     name_1 name_2
1 2    Amy    NaN
  3   Alex    NaN
  4    NaN  Billy
  5    NaN  Brian

如果我更改以下内容,它将不起作用,因为 raw_data 中的多索引键是重复的:

     raw_data = {
        'type_1': [1, 1],    
        'id_1': ['2', '2'],   #  <-- changed from 3 to 2
        'name_1': ['Alex', 'Amy']}

以及以下内容:

raw_datab = {
        'type_2': [1, 1],
        'id_2': ['2', '5'], #  <-- changed from 4 to 2
        'name_2': ['Billy', 'Brian']}

因此,AlexAmyBilly 都具有相同的多索引键 [1,2],所以 concat 失败:

cannot handle a non-unique multi-index!

但是重复的数据是有效的,无论如何我都需要连接它。这是我需要达到的结果(注意这应该是外连接,默认):

     name_1  name_2
1 2    Amy    Billy
  2   Alex    Billy
  5    NaN    Brian

Pandas 怎么可能做到这一点?

最佳答案

axis=1 更改为 axis=0(默认)

df = pd.concat(dfs)
df
Out[52]: 
            name_1 name_2
type_1 id_1              
1      2      Alex    NaN
       2       Amy    NaN
       4       NaN  Billy
       5       NaN  Brian

根据您的评论..

df_a.merge(df_b,left_on=['type_1','id_1'],right_on=['type_2','id_2'],how='outer').set_index(['type_2','id_2']).drop(['type_1','id_1'],1)
Out[80]: 
            name_1 name_2
type_2 id_2              
1      2      Alex  Billy
       2       Amy  Billy
       5       NaN  Brian

关于python - 需要处理具有非唯一多索引的串联数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49786769/

相关文章:

python - B 和 C 不工作(Python3)

python-3.x - 在 Python 3 中记录异常

python-3.x - os.path.exists 返回 false 但不会在 try/except block 中引发异常

python - 如何使用 NumPy 沿每一行和每一列应用我自己的函数

python - 用 NA 替换 pandas 数据框中所有出现的值的快速方法

python - 如何让 Pandas 根据出现次数为值添加递增后缀

php - 安装linux raspberry的mysql-server失败(没有剩余空间)

python - 如何从父目录导入模块? (单元测试目的)

python - 将列合并为一个字符分隔的列适用于所有行

python - Dynamodb 和 Boto3,在扫描中链接多个条件