首页 > 解决方案 > 如何从数据框列的某些行中删除字符?

问题描述

我有一个大DataFrame的需要清理,作为示例,请查看此数据框:

import pandas as pd

cars = {'Brand': ['Honda Civic','Toyota Corolla','Ford Focus','Audi A4','Suzuki'],
        'Price': ['22000.T','25000.T','27000','.TPX','.NKM1']
        }

df = pd.DataFrame(cars, columns = ['Brand', 'Price'])

print (df)

我想'.T'从单词的末尾删除,并且只'.'从包含的行的开头删除。

通过以下代码行,我可以删除'.T'

df['Price'].replace('.T', '', regex=True)

但它也'T''.TPX'

对此的任何建议表示赞赏。

0    22000
1    25000
2    27000
3       PX
4    .NKM1
Name: Price, dtype: object

也用于删除'.'当我添加此行时

f['Price'].replace('.', '', regex=True)

我得到了与预期不同的数据框

0    
1    
2    
3    
4    
Name: Price, dtype: object

标签: pythonregexpandasdataframedata-cleaning

解决方案


另一种方法是使用 and 来使用和numpy.where评估您的条件:str.startswithstr.endswith

import numpy as np

p = df['Price'].str
df['Price'] = np.where(p.startswith('.'),p.replace('.','',regex=True),
                         np.where(p.endswith('.T'),p.replace('.T','',regex=True),p))

这将检查是否df['Price']以 a 开头.或以 a 结尾.T并替换它们。

            Brand  Price
0     Honda Civic  22000
1  Toyota Corolla  25000
2      Ford Focus  27000
3         Audi A4    TPX
4          Suzuki   NKM1

推荐阅读