python 在panda Dataframe中查找模式

ctzwtxfj  于 2023-03-21  发布在  Python
关注(0)|答案(1)|浏览(112)

在c1_ind和c2_ind中的所有值中查找mode。我不想在每一列中查找mode。

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)

对于另一个示例,在c1_ind和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)
bvjxkvbb

bvjxkvbb1#

您可以使用filter来选择感兴趣的列(这里使用regex),然后使用stack,最后使用mode

df.filter(regex='C\d+_IND').stack().mode().iloc[0]
  • 注意,如果有多种模式,我们只保留一种。如果您想要所有模式,请删除iloc[0],可选替换为squeeze。*

输出:'Hold'

相关问题