Skip to main content
 首页 » 编程设计

python之如何缩短 DataFrame 中的某些子字符串

2024年11月24日22lyhabc

我在 DataFrame 中有一系列 SKU:[35641, 265689494123, 36492, 56526246546, 26412...]。

问题是 DataFrame 中的长条形码(如 56526246546)需要在某些点被截断。超过 5 的长度应触发删除过程,该过程会像列表中的 [7:12] 一样被截断。

我尝试使用以下代码,但没有任何优势:

if df.loc[len(df['SKU']) > 5]: 
    df.loc[df['SKU'].df.slice(start=7,stop=12)] 

我收到以下错误消息:

  KeyError                                  Traceback (most recent call last) 
c:\users\User\appdata\local\programs\python\python37\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance) 
   2656             try: 
-> 2657                 return self._engine.get_loc(key) 
   2658             except KeyError: 
 
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc() 
 
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc() 
 
pandas\_libs\index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type() 
 
KeyError: True 
 
During handling of the above exception, another exception occurred: 
 
KeyError                                  Traceback (most recent call last) 
<ipython-input-64-cea7b4ca2640> in <module> 
      1 #g[:] = (elem[:12] for elem in g) 
----> 2 if df.loc[len(df['SKU']) > 5]: 
      3     df.loc[df['SKU'].df.slice(start=7,stop=12)] 
 
c:\users\User\appdata\local\programs\python\python37\lib\site-packages\pandas\core\indexing.py in __getitem__(self, key) 
   1498  
   1499             maybe_callable = com.apply_if_callable(key, self.obj) 
-> 1500             return self._getitem_axis(maybe_callable, axis=axis) 
   1501  
   1502     def _is_scalar_access(self, key): 
 
c:\users\User\appdata\local\programs\python\python37\lib\site-packages\pandas\core\indexing.py in _getitem_axis(self, key, axis) 
   1911         # fall thru to straight lookup 
   1912         self._validate_key(key, axis) 
-> 1913         return self._get_label(key, axis=axis) 
   1914  
   1915  
 
c:\users\User\appdata\local\programs\python\python37\lib\site-packages\pandas\core\indexing.py in _get_label(self, label, axis) 
    139             raise IndexingError('no slices here, handle elsewhere') 
    140  
--> 141         return self.obj._xs(label, axis=axis) 
    142  
    143     def _get_loc(self, key, axis=None): 
 
c:\users\User\appdata\local\programs\python\python37\lib\site-packages\pandas\core\generic.py in xs(self, key, axis, level, drop_level) 
   3583                                                       drop_level=drop_level) 
   3584         else: 
-> 3585             loc = self.index.get_loc(key) 
   3586  
   3587             if isinstance(loc, np.ndarray): 
 
c:\users\User\appdata\local\programs\python\python37\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance) 
   2657                 return self._engine.get_loc(key) 
   2658             except KeyError: 
-> 2659                 return self._engine.get_loc(self._maybe_cast_indexer(key)) 
   2660         indexer = self.get_indexer([key], method=method, tolerance=tolerance) 
   2661         if indexer.ndim > 1 or indexer.size > 1: 
 
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc() 
 
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc() 
 
pandas\_libs\index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type() 
 
KeyError: True 

如何修复此代码?

P.S 由于我在将 dict 转换为 DataFrame 之前添加了代码,因此似乎会弹出一些错误消息。

请您参考如下方法:

根据你想要的输出,我觉得你可以使用:

df['SKU'] = df['SKU'].apply(lambda x: int(str(x)[6:11]) if len(str(x)) > 5 else x) 

输出:

     SKU 
0  35641 
1  49412 
2  36492 
3  46546 
4  26412