【问题标题】:Remove item in pandas dataframe that starts with a comment char [duplicate]删除以注释字符开头的熊猫数据框中的项目[重复]
【发布时间】:2019-05-18 07:03:54
【问题描述】:

我想删除以注释字符开头的 pandas 数据框中的所有行。例如:

>>> COMMENT_CHAR = '#'
>>> df
    first_name    last_name
0   #fill in here fill in here
1   tom           jones

>>> df.remove(df.columns[0], startswith=COMMENT_CHAR) # in pseudocode
>>> df
    first_name    last_name
0   tom           jones

这实际上是如何完成的?

【问题讨论】:

  • df.loc[~df.first_name.str.startswith('#')] 或类似的东西。该掩码的反转可以与df.drop 一起使用
  • 还有.reset_index(drop=True)
  • @user3483203 有没有办法通过使用索引而不是列名来做到这一点?
  • df.mask(df.iloc[:,0].str.startswith('#')).dropna()
  • @ChrisA 非常简洁,您想解释一下它是如何在答案中起作用的吗?我可以接受吗?

标签: python pandas


【解决方案1】:

设置

>>> data = [['#fill in here', 'fill in here'], ['tom', 'jones']]                                                       
>>> df = pd.DataFrame(data, columns=['first_name', 'last_name'])                                                       
>>> df                                                                                                                 
      first_name     last_name
0  #fill in here  fill in here
1            tom         jones

假设只有 first_name 列中的字符串很重要的解决方案:

>>> commented = df['first_name'].str.startswith('#')                                                                   
>>> df[~commented].reset_index(drop=True)                                                                              
  first_name last_name
0        tom     jones

解决方案假设您要删除 first_name OR last_name 列中的字符串以 '#' 开头的行:

>>> commented = df.apply(lambda col: col.str.startswith('#')).any(axis=1)                                             
>>> df[~commented].reset_index(drop=True)                                                                              
  first_name last_name
0        tom     jones

reset_index 的目的是重新标记从零开始的行。

>>> df[~commented]                                                                                                     
  first_name last_name
1        tom     jones
>>>                                                                                                                    
>>> df[~commented].reset_index()                                                                                       
   index first_name last_name
0      1        tom     jones
>>>                                                                                                                    
>>> df[~commented].reset_index(drop=True)                                                                              
  first_name last_name
0        tom     jones

【讨论】:

  • 您能否解释一下在通话结束时使用reset_index() 的目的以及为什么需要这样做?
  • @David542 确定 - 如果没有 reset_index,保留的每一行都会保留其原始行标签。在此示例中,剩余的行将具有标签 1。使用reset_index,您可以重新标记从0drop=True 开始的行,以防止将要删除的原始索引移动到列中。
  • 感谢您将其添加到答案中。
猜你喜欢
  • 1970-01-01
  • 2019-01-28
  • 1970-01-01
  • 1970-01-01
  • 2016-11-12
  • 2022-11-01
  • 2016-06-23
  • 2020-03-23
  • 2018-02-02
相关资源
最近更新 更多