【问题标题】:Filtering by column - multiple pd.arrays按列过滤 - 多个 pd.arrays
【发布时间】:2022-11-02 17:34:01
【问题描述】:

我在不同时间有来自相同测量的多个数据框。现在我想找到相关的测量值(可以通过一个名为 abmn 的列中的字符串来定位)。问题是我无法迭代,因为所有数据集都有不同的长度。 你知道有什么解决办法吗? 例子

df1 
| res | abmn   |
| 3   | 1234   |
| 0   | 1245   |
| 2   | 1256   |
df2
| res | abmn   |
| 1   | 1234   |
| 0   | 1256   |
| 2   | 1267   |

我只想要两个数据框

df1 
| res | abmn   |
| 3   | 1234   |
| 2   | 1256   |
df2
| res | abmn   |
| 1   | 1234   |
| 0   | 1256   |

我尝试了一个循环,但这不起作用,因为它们的长度不同。我想我设法得到了一个包含 abmn 值的所有字符串的列表(所有四个数据集中的所有值),但我还没有真正找到解决方案

【问题讨论】:

    标签: python


    【解决方案1】:

    这是您问题的可能答案。我首先查看两者共有的值,然后创建两个新数据框基于要保留的值。

    这是代码:

    import pandas as pd
    
    # generate the dataframes as per the example
    df1 = pd.DataFrame({"res":[3,0,2], "abmn":[1234,1245,1256]})
    df2 = pd.DataFrame({"res":[1,0,2], "abmn":[1234,1256,1267]})
    
    # identify the items to keep
    items_to_keep = []
    for item in df1['abmn']:
        if item in df2['abmn'].values:
            items_to_keep.append(item)
       
    # create new dataframes based on the list of items to keep
    new_df1 = df1[df1.abmn.isin(items_to_keep)]
    new_df2 = df2[df2.abmn.isin(items_to_keep)]
    
    # print the two new dataframes
    print("new_df1")
    print(new_df1)
    print("==========")
    print("new_df2")
    print(new_df2)
    

    输出:

    new_df1
       res  abmn
    0    3  1234
    2    2  1256
    ==========
    new_df2
       res  abmn
    0    1  1234
    1    0  1256
    


    请注意,即 for 循环,可以替换为列表理解:

    # identify the items to keep
    items_to_keep = [item for item in df1['abmn'] if item in df2['abmn'].values]
    

    【讨论】:

      【解决方案2】:

      非常感谢你的帮助!它工作得更好

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-14
        • 2021-08-27
        • 1970-01-01
        • 1970-01-01
        • 2020-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多