Skip to main content
 首页 » 编程设计

python之Pandas 元素比较和创建选择

2025年05月04日27shangdawei

在数据框中,我想将列的元素与值进行比较,并将通过比较的元素排序到新列中。

df = pandas.DataFrame([{'A':3,'B':10}, 
                       {'A':2, 'B':30}, 
                       {'A':1,'B':20}, 
                       {'A':2,'B':15}, 
                       {'A':2,'B':100}]) 
 
df['C'] = [x for x in df['B'] if x > 18] 

我无法找出问题所在以及为什么我得到:

ValueError: Length of values does not match length of index

请您参考如下方法:

我想你可以使用 loc与 boolean indexing :

print (df) 
   A    B 
0  3   10 
1  2   30 
2  1   20 
3  2   15 
4  2  100 
 
print (df['B'] > 18) 
0    False 
1     True 
2     True 
3    False 
4     True 
Name: B, dtype: bool 
 
df.loc[df['B'] > 18, 'C'] = df['B'] 
print (df) 
   A    B      C 
0  3   10    NaN 
1  2   30   30.0 
2  1   20   20.0 
3  2   15    NaN 
4  2  100  100.0 

如果您需要按条件选择,请使用 boolean indexing :

print (df[df['B'] > 18]) 
   A    B 
1  2   30 
2  1   20 
4  2  100 

如果需要更快的东西,请使用 where :

df['C'] = df.B.where(df['B'] > 18) 

时间(len(df)=50k):

In [1367]: %timeit (a(df)) 
The slowest run took 8.34 times longer than the fastest. This could mean that an intermediate result is being cached. 
1000 loops, best of 3: 1.14 ms per loop 
 
In [1368]: %timeit (b(df1)) 
100 loops, best of 3: 15.5 ms per loop 
 
In [1369]: %timeit (c(df2)) 
100 loops, best of 3: 2.93 ms per loop 

计时代码:

import pandas as pd 
 
df = pd.DataFrame([{'A':3,'B':10}, 
                       {'A':2, 'B':30}, 
                       {'A':1,'B':20}, 
                       {'A':2,'B':15}, 
                       {'A':2,'B':100}]) 
print (df) 
df = pd.concat([df]*10000).reset_index(drop=True) 
df1 = df.copy() 
df2 = df.copy() 
 
def a(df): 
    df['C'] = df.B.where(df['B'] > 18) 
    return df 
 
def b(df1):     
    df['C'] = ([x if x > 18 else None for x in df['B']]) 
    return df 
 
def c(df2):     
    df.loc[df['B'] > 18, 'C'] = df['B'] 
    return df 
 
print (a(df)) 
print (b(df1)) 
print (c(df2))