【问题标题】:Overlaying two pandas Dataframes or numpy arrays and creating a key-value dictionary覆盖两个 pandas 数据框或 numpy 数组并创建一个键值字典
【发布时间】:2017-03-02 15:53:14
【问题描述】:

我有两个形状为 3x3 的 CSV 文件。

文件 1 如下所示:

-1, 2,-1
-1,-1, 3
-1, 8, 9

和像这样的文件 2:

-1, 56,-1
-1,-1,  73
-1, 24, 100

我的目标是覆盖两个数组或DataFrames 并创建以下形式的字典:

dict = {2:56, 3:73, 8:24, 9:100}

我可以创建一些基于循环的东西,但我想知道是否有一种方法可以屏蔽或覆盖数组并创建相应的字典?

【问题讨论】:

    标签: python pandas numpy dictionary overlay


    【解决方案1】:

    您可以展平数据框、删除空值并对其进行 dict/zip 压缩:

    import pandas as pd
    
    # Load the data, converting -1 to NaN
    dfa = pd.read_csv('file1.csv', header=None, na_values=[-1])
    dfb = pd.read_csv('file2.csv', header=None, na_values=[-1])
    
    # Flatten the dataframes
    a = dfa.values.flatten()
    b = dfb.values.flatten()
    
    # Remove null values and cast back to ints (if that matters)
    # Note that both are filtered according to the key data
    a = a[~np.isnan(a)].astype(int)
    b = b[~np.isnan(a)].astype(int)
    
    # Zip to pair the lists, then convert to a dict
    d = dict(zip(a, b))
    

    【讨论】:

    • 感谢您的回复!
    • @Floriand 没问题!如果它解决了您的问题,您可以接受答案,以便人们知道它已解决,如果您喜欢该答案,您可以投票(尽管两者都不是必需的!)。
    猜你喜欢
    • 2022-09-28
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 2021-12-28
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多