1

Find mode among all values in c1_ind and c2_ind . I don't want to mode along each column.

import pandas as pd
import numpy as np
from scipy.stats import mode


list =[{"col1":123,"C1_IND    ":"Rev","C2_IND":"Hold"},
{"col1":456,"C1_IND    ":"Hold","C2_IND":"Rev"},
{"col1":123,"C1_IND    ":"Hold","C2_IND":"Service"},
{"col1":1236,"C1_IND    ":"Man","C2_IND":"Man"}]

df = pd.DataFrame.from_dict(list)
print(df)

For another example Find mode among all values in c1_ind and c3_ind


import pandas as pd
import numpy as np
from scipy.stats import mode


list =[{"col1":123,"C1_IND    ":"Rev","C2_IND":"Hold","C3_IND":"Hold"},
{"col1":456,"C1_IND    ":"Hold","C2_IND":"Rev","C3_IND":"Rev"},
{"col1":123,"C1_IND    ":"Hold","C2_IND":"Service","C3_IND":"Service"},
{"col1":1236,"C1_IND    ":"Man","C2_IND":"Man","C3_IND":"Man"}]

df = pd.DataFrame.from_dict(list)
print(df)
0

1 Answer 1

1

You can use filter to select the columns of interest (here by regex), then stack and finally use mode.:

df.filter(regex='C\d+_IND').stack().mode().iloc[0]

NB. If there are several modes, we only keep one. If you want all, remove the iloc[0], optionally replacing with squeeze.

Output: 'Hold'

4
  • Incase I received multiple values using squeeze, is there way to convert those values to list ?
    – pbh
    Mar 20 at 17:46
  • I got it . Thanks list=v.to_list() print(list)
    – pbh
    Mar 20 at 17:50
  • 1
    squeeze will just convert a series to scalar if there is only one item. You might want df.filter(regex='C\d+_IND').stack().mode().tolist()
    – mozway
    Mar 20 at 17:50
  • You have provided better option
    – pbh
    Mar 20 at 17:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.