Python 比较不同列的字符串长度上的数据帧
我试图得到不同列的字符串长度。似乎很直截了当:Python 比较不同列的字符串长度上的数据帧,python,pandas,dataframe,min,string-length,Python,Pandas,Dataframe,Min,String Length,我试图得到不同列的字符串长度。似乎很直截了当: df['a'].str.len() 但我需要将其应用于多个列。然后得到它的最小值 比如: df[['a','b','c']].str.len().min 我知道上面的方法行不通,但希望你能理解。列a,b,c都包含名称,我想检索最短的名称 另外,由于数据量巨大,我避免创建其他列以节省大小 我认为您需要理解列表,因为string函数仅适用于系列(column): 另一个使用应用的解决方案: print ([df[col].apply(len).mi
df['a'].str.len()
但我需要将其应用于多个列。然后得到它的最小值
比如:
df[['a','b','c']].str.len().min
我知道上面的方法行不通,但希望你能理解。列a
,b
,c
都包含名称,我想检索最短的名称
另外,由于数据量巨大,我避免创建其他列以节省大小 我认为您需要理解列表,因为
string
函数仅适用于系列(column
):
另一个使用应用的解决方案
:
print ([df[col].apply(len).min() for col in ['a','b','c']])
样本:
df = pd.DataFrame({'a':['h','gg','yyy'],
'b':['st','dsws','sw'],
'c':['fffff','','rr'],
'd':[1,3,5]})
print (df)
a b c d
0 h st fffff 1
1 gg dsws 3
2 yyy sw rr 5
print ([df[col].str.len().min() for col in ['a','b','c']])
[1, 2, 0]
计时:
#[3000 rows x 4 columns]
df = pd.concat([df]*1000).reset_index(drop=True)
In [17]: %timeit ([df[col].apply(len).min() for col in ['a','b','c']])
100 loops, best of 3: 2.63 ms per loop
In [18]: %timeit ([df[col].str.len().min() for col in ['a','b','c']])
The slowest run took 4.12 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 2.88 ms per loop
结论:
#[3000 rows x 4 columns]
df = pd.concat([df]*1000).reset_index(drop=True)
In [17]: %timeit ([df[col].apply(len).min() for col in ['a','b','c']])
100 loops, best of 3: 2.63 ms per loop
In [18]: %timeit ([df[col].str.len().min() for col in ['a','b','c']])
The slowest run took 4.12 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 2.88 ms per loop
apply
速度更快,但不适用于None
df = pd.DataFrame({'a':['h','gg','yyy'],
'b':[None,'dsws','sw'],
'c':['fffff','','rr'],
'd':[1,3,5]})
print (df)
a b c d
0 h None fffff 1
1 gg dsws 3
2 yyy sw rr 5
print ([df[col].apply(len).min() for col in ['a','b','c']])
TypeError:类型为“NoneType”的对象没有len()
按注释编辑:
#fail with None
print (df[['a','b','c']].applymap(len).min(axis=1))
0 1
1 0
2 2
dtype: int64
嘿@jezrael,看起来不错。回来后让我试一试。谢谢你的样品。不过,我正努力实现的是连续性。也就是说,对于a、b、c,另一列的答案是1,0,2是否存在None
value?此时不存在。我基本上删除了我使用的所有列的na。但也许在将来。好的,我也添加了一个没有的解决方案。
#fail with None
print (df[['a','b','c']].applymap(len).min(axis=1))
0 1
1 0
2 2
dtype: int64
#working with None
print (df[['a','b','c']].apply(lambda x: x.str.len().min(), axis=1))
0 1
1 0
2 2
dtype: int64