【问题标题】:Concat (Merge) Asymmetrical Data frame Table in Python Pandas to Create Relationship TablePython Pandas 中的 Concat (Merge) 非对称数据框表创建关系表
【发布时间】:2021-09-09 21:00:15
【问题描述】:

所以我有两个表,Table1 和 Table2

表1:

Key1 Key2
A1 B1

表2:

Key3 Key4 Key5
C1 D1 E1
C2 D2 E2
C3 D3 E3
... ... ...

我想结合表 3 中的两种材料

Key2 Key4
B1 D1
B1 D2
B1 D3
B1 ...

pandas 中是否有一个函数可以实现这一点

谢谢。

更新: 下面使用 Andrej Kesely 的解决方案。

代码:

#create relationship tables from dataframes above
userinforel = pd.merge(computerlist,userinfo , how="cross")[["Name","UserInfo.UserName"]] #works
monitorlistrel = pd.merge(computerlist,monitorlist , how="cross")[["Name","SerialNumber"]] #does not work

输出:

KeyError: "None of [Index(['Name', 'SerialNumber'], dtype='object')] are in the [columns]"
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
p:\Tech Support\LoginReport\LoginReport-To-SQL\LoginReport-to-SQL.py in <module>
    127 
    128 if __name__ == "__main__":
--> 129     main()

p:\Tech Support\LoginReport\LoginReport-To-SQL\LoginReport-to-SQL.py in main()
    117             json_to_sql(file.path) """
    118 
--> 119     json_to_sql('SK82-081AL101-20210903.0853.json') #loginreport v2
    120     #json_to_sql('SK82-081AL026-20210803.0849.json') #loginreport v1
    121 

p:\Tech Support\LoginReport\LoginReport-To-SQL\LoginReport-to-SQL.py in json_to_sql(JSONFILE)
     80         #create relationship tables from dataframes above
     81         userinforel = pd.merge(computerlist,userinfo , how="cross")[["Name","UserInfo.UserName"]]
---> 82         monitorlistrel = pd.merge(computerlist,monitorlist , how="cross")[["Name","SerialNumber"]]
     83         #printerlistrel = pd.merge(computerlist,printerlist , how="cross")[["Name","ID"]]
     84         #programlistrel = pd.merge(computerlist,programlist , how="cross")[["Name","IDName"]]

~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
   3459             if is_iterator(key):
   3460                 key = list(key)
-> 3461             indexer = self.loc._get_listlike_indexer(key, axis=1)[1]
   3462 
   3463         # take() does not accept boolean indexers

~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\indexing.py in _get_listlike_indexer(self, key, axis)
   1312             keyarr, indexer, new_indexer = ax._reindex_non_unique(keyarr)
   1313 
-> 1314         self._validate_read_indexer(keyarr, indexer, axis)
   1315 
   1316         if needs_i8_conversion(ax.dtype) or isinstance(

~\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\core\indexing.py in _validate_read_indexer(self, key, indexer, axis)
   1372                 if use_interval_msg:
   1373                     key = list(key)
-> 1374                 raise KeyError(f"None of [{key}] are in the [{axis_name}]")
   1375 
   1376             not_found = list(ensure_index(key)[missing_mask.nonzero()[0]].unique())

KeyError: "None of [Index(['Name', 'SerialNumber'], dtype='object')] are in the [columns]"

更新 2: 原来有与下面提到的 Andrej Kesely 类似的列名,使用后缀来解决问题。

#create relationship tables from dataframes above
userinforel = pd.merge(computerlist,userinfo, how="cross")[["Name","UserInfo.UserName"]] #works
monitorlistrel = pd.merge(computerlist,monitorlist, how="cross")[["Name_x","SerialNumber_y"]] #works

【问题讨论】:

    标签: python pandas database dataframe


    【解决方案1】:

    您可以尝试交叉合并:

    df_out = pd.merge(df1, df2, how="cross")[["Key2", "Key4"]]
    print(df_out)
    

    打印:

      Key2 Key4
    0   B1   D1
    1   B1   D2
    2   B1   D3
    

    【讨论】:

    • 嗨,这适用于只有一行的表之一,但是当我对另一个多行的表执行相同操作时,它会显示一条错误消息:KeyError:“没有 [Index (['Name', 'SerialNumber'], dtype='object')] 在 [columns]"
    • @CrisantoIII 在df1、df2 中是否有共同的列名?如果是,则需要相应添加后缀_x或_y。
    • @CrisantoIII 例如["Name_x","SerialNumber_y"],但如果没有看到你的真实数据就很难分辨。
    猜你喜欢
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-10
    • 2018-03-15
    • 1970-01-01
    • 2021-12-06
    相关资源
    最近更新 更多