【问题标题】: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.lowerstr.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)
    

    【讨论】:

      猜你喜欢
      • 2020-12-31
      • 2018-04-26
      • 2018-11-01
      • 2021-09-25
      • 2017-11-28
      • 2018-08-08
      • 2014-08-18
      • 1970-01-01
      相关资源
      最近更新 更多