-2

Kindly help me to make a function out of code. Thanks

my_words = ''

for w in data3['any_column'].astype(str).values:
    my_words += '{} '.format(w.lower())
my_words = my_words.split(' ')
word_counter = {}
for w in my_words:
    if w not in word_counter:
        word_counter[w] = 1
    if w in word_counter:
        word_counter[w] += 1
word_counter_series = pd.Series(word_counter)
word_counter_series.sort_values(ascending=False)
letdatado
  • 93
  • 1
  • 11
  • Please repeat [on topic](https://stackoverflow.com/help/on-topic) and [how to ask](https://stackoverflow.com/help/how-to-ask) from the [intro tour](https://stackoverflow.com/tour). “Teach me how to write a function” is not a Stack Overflow issue. We expect you to make an honest attempt, and *then* ask a *specific* question about your algorithm or technique. Stack Overflow is not intended to replace existing documentation and tutorials. – Prune Jun 29 '21 at 18:32
  • Also, your follow-up questions are far too broad. Your post distills to "do my homework in the best way possible", with requests for tutorial explanations. – Prune Jun 29 '21 at 18:34
  • A pro such as you should refrain from unnecessary exaggeration. I never asked the experts here to give tutorial explanations. I am aware that I am still learning and should not bother others. Anyways, Thanks for your kind response! – letdatado Jun 29 '21 at 19:22
  • Does this answer your question? [Counting the Frequency of words in a pandas data frame](https://stackoverflow.com/questions/46786211/counting-the-frequency-of-words-in-a-pandas-data-frame) – Henry Ecker Jun 29 '21 at 21:16
  • @HenryEcker Yes!!! It didn't just answer my question but also helped me know many other ways I could proceed with my approach. Thanks a lot for helping me out once again!! I post my issues once I am done spending hours on those. Thanks! – letdatado Jun 30 '21 at 07:24
  • @HenryEcker The question is just like the one I asked. I don't know why I receive discouragement from the questions I ask or even the answers I post. – letdatado Jun 30 '21 at 07:30

2 Answers2

0

An easier alternative is using the Counter class.

from collections import Counter
counts = Counter(my_words)

The result will be a dictionary-like object that associates the words and how many times they appear in the list.

VentricleV
  • 40
  • 6
0

You can use Counter to do it. here is an example:

from collections import Counter

def word_counter(text):
    words_list = text.split(" ")
    return Counter(words_list)

You can also see this question's second answer for more details.