社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python delete from date列行包含字符串

rahul • 7 年前 • 2132 次点击  

我加入了两个数据框架:一个包含年度日期,另一个使用日期范围创建月度日期。
在连接两个数据帧之后,有一些重复的日期值,我为其分配了后缀'\u dup'。
现在,我如何删除包含“_dup”值的行。我的数据帧如下:

enter image description here

现在,我使用以下代码删除/删除包含“\u dup”的日期行

for i in range (117):
if df5.iloc[i,0].str.contains ('_dup'):
    del df5.loc[i,0]

我得到错误:


AttributeError                            Traceback (most recent call last)
<ipython-input-171-ae80d413249e> in <module>()
      1 for i in range (117):
----> 2     if df5.iloc[i,0].str.contains ('_dup'):
      3         del df5.loc[i,0]

AttributeError: 'str' object has no attribute 'str'

我也试过密码:

df5[~df5.index.str.contains("_dup")]

错误在于:

AttributeError: Can only use .str accessor with string values (i.e. inferred_type is 'string', 'unicode' or 'mixed')`
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/49838
文章 [ 1 ]  |  最新文章 7 年前
Toby Petty
Reply   •   1 楼
Toby Petty    7 年前

你的问题是 df5.iloc[i,0] 访问单个 str 列中的数据点,因此无法应用 str公司 再次发挥作用。你可以申请 str.contains 同时对整个列执行以下操作:

df = df.loc[~df["col_name"].str.contains("dup")]

然而 str.包含 如果列中存在混合数据类型,则函数将不起作用。在这种情况下,您需要首先转换类型( df["col_name"] = df["col_name"].astype(str) ). 或者,如果重复的值是唯一具有字符串类型的数据点,则只需根据以下类型进行筛选:

df.loc[~df["col_name"].apply(lambda x: isinstance(x, str))]