python - 如何从数据框列的某些行中删除字符?
问题描述
我有一个大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
解决方案
另一种方法是使用 and 来使用和numpy.where
评估您的条件:str.startswith
str.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
推荐阅读
- python-3.x - 将默认日期时间对象值赋予 pandas.to_datetime()
- php - 分类学的帖子在wordpress中根本没有显示
- php - 这个(病毒?)代码有什么作用?
- python - Pandas/matplotlib 没有绘制所有列数据
- android - 如何删除由日历设置的通知?
- database - 天蓝色数据仓库中的死锁错误
- python - tensorflow-gpu 1.8.0 ImportError:libcudnn.so.7:无法打开共享对象文件:没有这样的文件或目录
- python-3.x - setuptools,在本地系统上使用包而不是从 PyPI 获取它
- jenkins - 詹金斯与 msbuild
- python - Python根据字典值降序的第一个元素打印字典