python比较长度,python – 比较不同列的字符串长度的数据帧

我试图获取不同列的字符串长度.看起来很简单:

df['a'].str.len()

但我需要将它应用于多个列.然后获得最低限度.

就像是:

df[['a','b','c']].str.len().min

我知道上面的内容不起作用,但希望你能得到这个想法.列a,b,c都包含名称,我想检索最短的名称.

此外,由于数据量巨大,我正在避免创建其他列以节省大小.

解决方法:

我认为你需要列表理解,因为字符串函数只适用于Series(列):

print ([df[col].str.len().min() for col in ['a','b','c']])

另一个解决方案适用:

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

结论:

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: object of type ‘NoneType’ has no len()

print ([df[col].str.len().min() for col in ['a','b','c']])

[1, 2.0, 0]

编辑评论:

#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

标签:python,dataframe,pandas,min,string-length

来源: https://codeday.me/bug/20190623/1267450.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值