Python 计算列中的字符数
是否有一种方法可以显式计算字符串列中的字符数,并按其各自的单词对它们进行分组Python 计算列中的字符数,python,pandas,Python,Pandas,是否有一种方法可以显式计算字符串列中的字符数,并按其各自的单词对它们进行分组 df["text"]=[["Hello how are you?"],["I am fine"]] Then the counter should be df["count"]= [[0-4 6-8 10-12 14-16 17],[0 2-3 5-8]] 据我所知,您的要求没有任何功能,但您可以: import re import pa
df["text"]=[["Hello how are you?"],["I am fine"]]
Then the counter should be
df["count"]= [[0-4 6-8 10-12 14-16 17],[0 2-3 5-8]]
据我所知,您的要求没有任何功能,但您可以:
import re
import pandas as pd
# setup
df = pd.DataFrame(data=[["Hello how are you?"], ["I am fine"]], columns=['text'])
def extract_spans(m):
"""Convert span to required string representation"""
start, end = m.span()
return f'{start}-{end - 1}' if end - start > 1 else f'{start}'
# create count column
df['count'] = [' '.join([extract_spans(m) for m in re.finditer(r'([^\w\s_]|\w+)', v)]) for v in df['text'].tolist()]
print(df)
输出
text count
0 Hello how are you? 0-4 6-8 10-12 14-16 17
1 I am fine 0 2-3 5-8
那么pandas列是一个字符串?你能补充一个更有意义的例子吗?这是一项任务,不是一个问题。你试过什么?你的方法在什么时候失败了?