python - 连接 2 个数据框并创建父子关系?

标签 python pandas

我有 2 个数据帧父级和子级,我想以 groupby 方式连接它们

df_parent

           parent  parent_value
    0   Super Sun             0
    1  Alpha Mars             4
    2       Pluto             9

df_child

                   child  value
    0         Planet Sun    100
    1  one Sun direction    101
    2     Ice Pluto Tune    101
    3       Life on Mars     99
    4         Mars Robot    105
    5          Sun Twins    200 

我希望输出按顺序排列 order = ['Sun', 'Pluto', 'Mars']

Sun
-childs
Pluto
-childs
Mards
-childs

我想通过关键字找到 child ,请引用parent_dict

parent_dict = {'Super Sun': 'Sun',
           'Alpha Mars': 'Mars',
           'Pluto': 'Pluto'}

预期输出

    child         value
0   Super Sun             0 # parent
1   Planet Sun          100 # child  
2   one Sun direction   101 # child   
3   Sun Twins           200 # child  
4   Pluto                 9 # parent
5   Ice Pluto Tune      101 # child       
6   Alpha Mars            4 # parent
7   Life on Mars         99 # child    
8   Mars Robot          105 # child    

到目前为止,我已经尝试迭代主列表和两个 dfs,但预期的输出没有出现,这是我的代码

output_df = pd.DataFrame()
for o in order:
    key = o
    for j, row in df_parent.iterrows():
        if key in row[0]:
            output_df.at[j, 'parent'] = key
            output_df.at[j, 'value'] = row[1]
            for k, row1 in df_child.iterrows():
                if key in row1[0]:
                    output_df.at[j, 'parent'] = key
                    output_df.at[j, 'value'] = row[1]              

print(output_df)

输出:

  parent  value
0    Sun    0.0
2  Pluto    9.0
1   Mars    4.0

最佳答案

经过一些准备后,您可以对两个数据帧使用append。首先在 df_parentdf_child 中创建一个列关键字,用于稍后排序。为此,您可以使用 np.select如:

import pandas as pd
order = ['Sun', 'Pluto', 'Mars']
condlist_parent = [df_parent['parent'].str.contains(word) for word in order]
df_parent['keyword'] = pd.np.select(condlist = condlist_parent, choicelist = order, default = None)
condlist_child = [df_child['child'].str.contains(word) for word in order]
df_child['keyword'] = pd.np.select(condlist = condlist_child, choicelist = order, default = None)

df_parent 为例:

       parent  parent_value keyword
0   Super Sun             0     Sun
1  Alpha Mars             4    Mars
2       Pluto             9   Pluto

现在您可以使用 append 以及 Categorical根据列表顺序对数据帧进行排序。 rename 用于适应您的预期输出,并让 append 按需要工作(两个数据框中的列应具有相同的名称)。

df_all = (df_parent.rename(columns={'parent':'child','parent_value':'value'})
                     .append(df_child,ignore_index=True))
# to order the column keyword with the list order
df_all['keyword'] = pd.Categorical(df_all['keyword'], ordered=True, categories=order)
# now sort_values by the column keyword, reset_index and drop the column keyword
df_output = (df_all.sort_values('keyword')
                  .reset_index(drop=True).drop('keyword',1)) # last two methods are for cosmetic

输出为:

               child  value
0          Super Sun      0
1         Planet Sun    100
2  one Sun direction    101
3          Sun Twins    200
4              Pluto      9
5     Ice Pluto Tune    101
6         Alpha Mars      4
7       Life on Mars     99
8         Mars Robot    105

注意:按“关键字”排序后,父级位于子级之前的事实是 df_child 附加到 df_parent,而不是相反。

关于python - 连接 2 个数据框并创建父子关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51176688/

相关文章:

python - 如何在 python/pandas 中解压缩/解聚合分层数据?

python - 日期的正则表达式在 python 的 RE 模块中不匹配

python - 来自 Python 计数表的箱线图

python - 从 dataframe.iloc 读取值太慢,并且 dataframe.values 出现问题

python - pandas dataframe - 根据列标题更改值

python - 为什么 pandas 不能处理绘图中的小数?

javascript - 如何在Python中下载点击播放音频文件

python - 与数据框和数组一起使用时如何使用 scipy griddata

Python 3.3 IndexError 没有意义

python - CNN索引错误: Target 2 is out of bounds