【问题标题】:Remove first three characters using python [duplicate]使用python删除前三个字符[重复]
【发布时间】:2021-09-22 05:15:37
【问题描述】:

我有一个我在 python 中读取的数据。在“标题”列中,很少有行具有我想要删除的“新”等额外字符。我试图找到正确的代码,但我找不到任何代码,当我尝试自己的代码时,我得到了错误。任何人都可以帮忙!!!提前致谢。 title data

if indeed['title'] == indeed.loc[indeed['title'].str.startswith('new')].copy():
    indeed['title'].str[3:]

错误

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-34-486b16b22bea> in <module>
----> 1 if indeed['title'] == indeed.loc[indeed['title'].str.startswith('new')].copy():
      2     indeed['title'].str[3:]

~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py in __nonzero__(self)
   1325     def __nonzero__(self):
   1326         raise ValueError(
-> 1327             f"The truth value of a {type(self).__name__} is ambiguous. "
   1328             "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
   1329         )

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

【问题讨论】:

  • 嗨@HenryEcker 非常感谢您的帮助。
  • 链接的副本有更好的选择indeed['title'] = indeed['title'].str.extract('(?:new)?(.*)', expand=False)indeed['title'] = indeed['title'].str.replace('^new', '', regex=True)同样,您接受的答案也有效。

标签: python pandas csv


【解决方案1】:

如果我理解正确,我会阅读该列并搜索前 3 个字符 =='new',如果匹配,则返回字符串中不包含前 3 个字符的列,否则按原样返回该列。

import pandas as pd
import numpy as np

mydata = pd.DataFrame(['software developer','newgis developer','javascript developer','newhr partner'])
mydata.columns=['title']
mydata['newcol']=np.where(mydata['title'].str[:3]=='new', mydata['title'].str[3:], mydata['title'])

print(mydata)  
                  title                newcol
0    software developer    software developer
1      newgis developer         gis developer
2  javascript developer  javascript developer
3         newhr partner            hr partner

【讨论】:

  • 这确实可以做到这一点,但它比仅仅使用库效率低很多
  • 亨利埃克版效率更高
  • @ifly6 非常感谢您帮助我。这两种方法都工作得很好
猜你喜欢
  • 2014-03-21
  • 1970-01-01
  • 2016-08-30
  • 1970-01-01
  • 2016-11-01
  • 1970-01-01
  • 2021-07-20
  • 2017-02-15
  • 1970-01-01
相关资源
最近更新 更多