【问题标题】:Remove the rows from pandas dataframe, that has sentences longer than certain word length从 pandas 数据框中删除句子长度超过特定字长的行
【发布时间】:2019-10-27 01:19:41
【问题描述】:

我想从 pandas 数据框中删除行,其中包含长度大于所需长度的特定列中的字符串。

例如:

输入框:

X    Y
0    Hi how are you.
1    An apple
2    glass of water
3    I like to watch movie

现在,假设我想从数据框中删除长度大于或等于 4 的字符串的行。

所需的输出帧必须是:

X    Y
1    An apple
2    glass of water

删除列“X”中值为 0,3 的行,因为第 0 列中的单词数为 4,第 3 列中的单词数分别为 5。

【问题讨论】:

  • @anky_91 greater than or equal to 4

标签: python string pandas split


【解决方案1】:

首先按空格拆分值,通过Series.str.len 获取行数并通过倒置条件检查>=<Series.ltboolean indexing

df = df[df['Y'].str.split().str.len().lt(4)]
#alternative with inverted mask by ~
#df = df[~df['Y'].str.split().str.len().ge(4)]
print (df)
   X               Y
1  1        An apple
2  2  glass of water

【讨论】:

    【解决方案2】:

    你可以数空格:

    df[df.Y.str.count('\s+').lt(3)]
    
       X               Y
    1  1        An apple
    2  2  glass of water
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-01
      • 2020-12-12
      • 2019-11-19
      • 1970-01-01
      • 2017-08-12
      • 2020-03-11
      • 1970-01-01
      • 2020-03-19
      相关资源
      最近更新 更多