【问题标题】:Number of unique values in columns in two pandas dataframe两个熊猫数据框中列中唯一值的数量
【发布时间】:2017-05-19 05:47:38
【问题描述】:

我有两个 pd.DataFrame 对象(从 .csv 文件读取),比如说,

1, 2
1, 3
2, 4

2, 1
1, 2
3, 3

假设DataFrame 被命名为data1data2。所以我可以很容易地计算data1data2每一列中唯一值的数量,分别使用

 uniques = data.apply(pd.Series.nunique)

data 分别替换为 data1data2。所以我会得到2, 3 对应data13, 3 对应data2。有没有办法(除了连接DataFrame's)以便在这两个DataFrame's 组合时获得唯一值的数量?我想得到3, 4

【问题讨论】:

    标签: python pandas dataframe unique


    【解决方案1】:
    #use numpy unique to count uninues after combining same columns from both DF.
    
    len(np.unique(np.c_[df1.iloc[:,0],df2.iloc[:,0]]))
    Out[1398]: 3
    
    len(np.unique(np.c_[df1.iloc[:,1],df2.iloc[:,1]]))
    Out[1399]: 4
    

    【讨论】:

      【解决方案2】:

      我认为不会。先需要concat

      df = pd.concat([df1,df2]).apply(pd.Series.nunique)
      print (df)
      a    3
      b    4
      dtype: int64
      

      【讨论】:

        【解决方案3】:

        另一种适用于任意数量数据帧的替代方法:

        dfs = [df1, df2]
        print([
            len(set(np.concatenate([df[colname].unique() for df in dfs])))
            for colname in dfs[0]
        ])
        [3, 4]
        

        请注意,这仅适用于所有数据框具有相同列名的情况。

        我认为concat 是最好的选择,除非你的数据框已经填满了你的本地内存:concatenating will copy

        【讨论】:

        • 我想避免串联。这是香草!
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-16
        • 1970-01-01
        • 2015-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多