如何对 python 列表或数组的每个单独元素进行切片



我有一个从熊猫系列派生出来的python列表,如下所示:

dsa = pd.Series(crew_data['Work Type'])
disc = [dsa]
print(disc)

输出如下:

[0      Disc - Standard Removal & Herbicide 
1      Disc - Standard Removal & Herbicide  
2                            Standard Trim  
3                       Disc - Hazard Tree  
4                       Disc - Hazard Tree  
...                   
134                     Disc - Hazard Tree  
135                     Disc - Hazard Tree  
136                     Disc - Hazard Tree  
137                     Disc - Hazard Tree  
138                     Disc - Hazard Tree  
Name: Work Type, Length: 139, dtype: object]

现在下一步是切片每个元素的前 4 个字符,以便返回的值为 Disc

在单个字符串上执行时,这似乎很简单,但是当由于某种原因尝试使用列表执行此操作时,似乎几乎是不可能的。这可以在 Excel 中使用公式 =LEFT(A1,4( 简单地完成,所以它肯定可以在 python 中像简单一样完成吗?

如果有人有解决方案,那就太好了。

使用示例数据帧

In [138]: df                                                                                     
Out[138]: 
col1  col2 col3 newcol
0    a     1    x    Wow
1    b     2    y    Dud
2    c     1    z    Wow
In [139]: df['newcol']                                                                           
Out[139]: 
0    Wow
1    Dud
2    Wow
Name: newcol, dtype: object
In [140]: type(_)                                                                                
Out[140]: pandas.core.series.Series

选择一列会给我一个系列;不需要另一个系列包装器

In [141]: pd.Series(df['newcol'])                                                                
Out[141]: 
0    Wow
1    Dud
2    Wow
Name: newcol, dtype: object

我们可以把它放在一个列表中,但这没有任何好处:

In [142]: [pd.Series(df['newcol'])]                                                              
Out[142]: 
[0    Wow
1    Dud
2    Wow
Name: newcol, dtype: object]
In [143]: len(_)                                                                                 
Out[143]: 1

我们可以将值提取为 numpy 数组:

In [144]: pd.Series(df['newcol']).values                                                         
Out[144]: array(['Wow', 'Dud', 'Wow'], dtype=object)

我们可以对数组或序列的每个元素应用字符串切片 - 使用列表推导

In [145]: [astr[:2] for astr in _144]                                                            
Out[145]: ['Wo', 'Du', 'Wo']
In [146]: [astr[:2] for astr in _141]                                                            
Out[146]: ['Wo', 'Du', 'Wo']

列表理解不一定是最"高级"的方式,但这是一个好的开始。 实际上它接近最佳,因为切片字符串必须使用字符串方法;没有其他人实现字符串切片。

pandas有一个str方法,用于将字符串方法应用于序列:

In [147]: ds = df['newcol']  
In [151]: ds.str.slice(0,2)        # or ds.str[:2]                                                               
Out[151]: 
0    Wo
1    Du
2    Wo
Name: newcol, dtype: object

这比列表理解更干净、更漂亮,但实际上更慢。

我可能错过了问题的要点,但这里有一个正则表达式实现。

import re
# Sample data
disc = ['                       Disc - Standard Removal & Herbicide ',
'      Disc - Standard Removal & Herbicide  ',
'                           Standard Trim  ',
'                       Disc - Hazard Tree',
'                      Disc - Hazard Tree ',]
# Regular Expression pattern
# We have Disc in parenthesis because that's what we want to capture.
# Using re.search(<pattern>, <string>).group(1) returns the first matching group. Using just
# re.search(<pattern>, <string>).group() would return the entire row.
disc_pattern = r"s+?(Disc)s+?"
# List comprehension that skips rows without 'Disc'
[re.search(disc_pattern, i).group(1) for i in disc if re.match(disc_pattern, i)]

输出:

['Disc', 'Disc', 'Disc', 'Disc']

相关内容

最新更新