【问题标题】:String function on a pandas series熊猫系列上的字符串函数
【发布时间】:2018-04-17 13:34:06
【问题描述】:
我想将以下字符串函数 text.lower 用于 Pandas 系列而不是文本文件。尝试了不同的方法将系列转换为列表然后字符串,但没有运气。我仍然无法直接使用以下功能。非常感谢您的帮助。
def words(text):
return re.findall(r'\w+', text.lower())
WORDS = Counter(words(open('some.txt').read()))
【问题讨论】:
标签:
python
string
pandas
series
【解决方案1】:
我认为你的功能需要apply:
s = pd.Series(['Aasa dsad d','GTH rr','SSD'])
print (s)
0 Aasa dsad d
1 GTH rr
2 SSD
dtype: object
def words(text):
return re.findall(r'\w+', text.lower())
print (s.apply(words))
0 [aasa, dsad, d]
1 [gth, rr]
2 [ssd]
dtype: object
但在 pandas 中最好使用 str.lower 和 str.findall,因为还可以使用 NaNs:
print (s.str.lower().str.findall(r'\w+'))
0 [aasa, dsad, d]
1 [gth, rr]
2 [ssd]
dtype: object
【解决方案2】:
这样的?
from collections import Counter
import pandas as pd
series = pd.Series(['word', 'Word', 'WORD', 'other_word'])
counter = Counter(series.apply(lambda x: x.lower()))
print(counter)