【问题标题】:how can i shorten this looping over the table time procces我怎样才能缩短这个循环表时间过程
【发布时间】:2022-01-04 01:18:18
【问题描述】:

我想总结“文本”列中超过 8 个字母的单词数/ 该表有超过 500,000 个值。 我对熊猫还不够熟悉。


def howmany8(array):  //returns the amount of words above 8 letter
  counter=0;
  for i in range(len(array)):
    if(len(array[i])>8):
      counter+=counter
  return counter 


newdf= df;
newdf.dropna(subset = ['text'])
newdf['wordssum']=newdf['text']

for i in range(len(newdf['text'])):
  newdf['wordssum'][i]= howmany8(re.split("\s",newdf['text'][i]))
print(newdf['words'].sum())

【问题讨论】:

标签: python regex pandas


【解决方案1】:

您似乎将“单词”视为非空白字符序列。如果是这种情况,您可以使用

df.dropna(subset=['text'], inplace=True)         # Remove NA values
df['wordssum'] = df['text'].str.count(r'\S{8,}') # Count occurrences of 8+ non-whitespace chunks
print(df['wordssum'].sum())                      # Print the sum of 'wordssum' column

如果你只想计算 8+ 个字母个单词,也就是整个单词,你需要使用

df['wordssum'] = df['text'].str.count(r'\b[^\W\d_]{8,}\b') # Count occurrences of whole 8+ letter words

或者,如果您不关心下划线或数字是否可以“粘贴”到字母:

df['wordssum'] = df['text'].str.count(r'[^\W\d_]{8,}') # Count occurrences of 8+ letter chunks

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 2020-10-08
    • 2020-08-14
    • 1970-01-01
    • 2021-07-14
    • 2017-06-25
    • 2020-06-07
    相关资源
    最近更新 更多