【问题标题】:How to compare decimal numbers available in columns of pandas dataframe?如何比较熊猫数据框列中可用的十进制数?
【发布时间】:2017-01-27 22:10:38
【问题描述】:

我想比较 Pandas 数据帧的两列中可用的十进制值。

我有一个数据框:

data = {'AA' :{0:'-14.35',1:'632.0',2:'619.5',3:'352.35',4:'347.7',5:'100'},
        'BB' :{0:'-14.3500',1:'632.0000',2:'619.5000',3:'352.3500',4:'347.7000',5:'200'}
       }
df1 = pd.DataFrame(data)
print df1

数据框如下所示:

       AA        BB
0  -14.35  -14.3500
1   632.0  632.0000
2   619.5  619.5000
3  352.35  352.3500
4   347.7  347.7000
5   100    200

我想比较 AABB 列。如上面的数据框所示,除了 5th 行之外,两列的值是相同的。唯一的问题是尾随零。

如果AABB 列相同,那么我希望第三列中这些比较的结果为Result,即TrueFalse

预期结果:

       AA        BB   Result
0  -14.35  -14.35    True
1   632.0  632.0     True
2   619.5  619.5     True
3  352.35  352.35    True
4   347.7  347.7     True
5   100    200       False

如何比较这些十进制值?

【问题讨论】:

    标签: python pandas indexing dataframe conditional-statements


    【解决方案1】:

    您需要通过astype 将列转换为float,然后比较列,因为列中的值typestring。然后使用mask 并作为条件使用布尔列Result

    print (type(df1.ix[0,'AA']))
    <class 'str'>
    
    print (type(df1.ix[0,'BB']))
    <class 'str'>
    
    df1['Result'] = df1.AA.astype(float) == df1.BB.astype(float)
    df1.BB = df1.BB.mask(df1.Result,df1.AA)
    print (df1)
           AA      BB Result
    0  -14.35  -14.35   True
    1   632.0   632.0   True
    2   619.5   619.5   True
    3  352.35  352.35   True
    4   347.7   347.7   True
    5     100     200  False
    

    ix 的另一种解决方案:

    df1['Result'] = df1.AA.astype(float) == df1.BB.astype(float)
    df1.ix[df1.Result, 'BB'] = df1.AA
    print (df1)
           AA      BB Result
    0  -14.35  -14.35   True
    1   632.0   632.0   True
    2   619.5   619.5   True
    3  352.35  352.35   True
    4   347.7   347.7   True
    5     100     200  False
    

    时间安排

    #len(df) = 6k
    df1 = pd.concat([df1]*1000).reset_index(drop=True)
    
    In [31]: %timeit df1.ix[df1.Result, 'BB'] = df1.AA
    The slowest run took 4.88 times longer than the fastest. This could mean that an intermediate result is being cached.
    1000 loops, best of 3: 1.19 ms per loop
    
    In [33]: %timeit df1.BB = df1.BB.mask(df1.Result,df1.AA)
    1000 loops, best of 3: 900 µs per loop
    

    【讨论】:

    • @jezrael- 请查看我的预期结果。如果两列相等,那么我希望 BB 列与 AA 相同。
    • 对不起,请稍等。
    • @jezrael- 哪个是快速掩码或 ix?
    • 真实数据的DataFrame的大小是多少?
    • @jezrael- 可能在 1500 到 10000 之间变化。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    • 2017-01-27
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    相关资源
    最近更新 更多