0

I have Pandas DataFrame and I am trying to create a list freqs that contains the frequency of elements of a column (of the DataFrame) matching the last column of the DataFrame.

freqs = []
for i in range(len(df.colums)-1):
    counter = 0
    result = row[-1]
    for row in df.iterrows():
        if row[i] == result:
            counter += 1
    freqs.append(counter / len_df)
print(freqs)

This is the code I have written but I find it too slow and less close to the panda way of solving it.

Siddhesh Agarwal
  • 159
  • 1
  • 12
  • 1
    https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.value_counts.html - try value_counts with normalize=True. Would that work? – ShyGuyRyRyNewlyTheDataGuy Jun 06 '22 at 13:46
  • Can you provide some sample data and expected results? I'm not sure I understand exactly what you are looking for – ArchAngelPwn Jun 06 '22 at 13:51
  • Your code doesn't make much sense to me. You're iterating over columns with `i` and then calling `row[i]` for each row? – rafaelc Jun 06 '22 at 13:56

1 Answers1

0

The below line should help...

df['ColumnName'].value_counts().to_dict() 

Associated Documentation : https://pandas.pydata.org/docs/reference/api/pandas.Series.value_counts.html

This might be a duplicate of : Count frequency of values in pandas DataFrame column and so, if the answer helps - kindly close this question.

Sudu
  • 1
  • 2