python - 给定 n 列的数据框,我想计算每列中特定数字的频率

标签 python pandas

''' 数据框就像

1 2 4 ....n

0 2 0 ....n

1 0 4 ....n

0 0 4 ....n

现在我想从第 1 列计数 1,从第 2 列计数 2,从第 3 列计数 4 等等。

但我也想通过添加像这样的列来计算一些值

1+2、1+4、2+4、1+2+4

0+2、0+0、2+0、0+2+0

1+0、1+4、0+4、1+0+4

0+0、0+4、0+4、0+0+4

从上面的列中分别数出 3 数 5 数 6 数 7。

从 a 列计数 1 个,从 b 列计数 2 个,从 a+b 列计数 3 个,从 c 列计数 4 个,从 a+c 列计数 5 个,从 b+c 列计数 6 个,从 a+b+ 列计数 7 个C。像这样。

将所有这些值/数字存储在列表、数组或数据框中,例如

值/数字、标题、频率

1、a、2

2、b、2

3、a+b、1

4、c、3

5、a+c、2

6、b+c、1

7,a+b+c,1

'''

最佳答案

使用previous solution第一:

from itertools import chain, combinations
#https://stackoverflow.com/a/5898031
comb = chain(*map(lambda x: combinations(df.columns, x), range(2, len(df.columns)+1)))

cols = df.columns
for c in comb:
    df[f'{"+".join(c)}'] = df.loc[:, c].sum(axis=1)
print (df)
   a  b  c  a+b  a+c  b+c  a+b+c
0  1  2  4    3    5    6      7
1  0  2  0    2    0    2      2
2  1  0  4    1    5    4      5
3  0  0  4    0    4    4      4

df1 = df.apply(pd.value_counts)
print (df1)
     a    b    c  a+b  a+c  b+c  a+b+c
0  2.0  2.0  1.0  1.0  1.0  NaN    NaN
1  2.0  NaN  NaN  1.0  NaN  NaN    NaN
2  NaN  2.0  NaN  1.0  NaN  1.0    1.0
3  NaN  NaN  NaN  1.0  NaN  NaN    NaN
4  NaN  NaN  3.0  NaN  1.0  2.0    1.0
5  NaN  NaN  NaN  NaN  2.0  NaN    1.0
6  NaN  NaN  NaN  NaN  NaN  1.0    NaN
7  NaN  NaN  NaN  NaN  NaN  NaN    1.0

然后DataFrame.aggDataFrame.idxmaxDataFrame.max对于新的 DataFrame,DataFrame.reset_index对于索引中的列和最后一个重命名列:

c = {'index':'Values/Number','idxmax':'Title','max':'Frequency'}
df2 = df1.agg(['idxmax','max'], axis=1).reset_index().rename(columns=c)
print (df2)
   Values/Number  Title Frequency
0              0      a         2
1              1      a         2
2              2      b         2
3              3    a+b         1
4              4      c         3
5              5    a+c         2
6              6    b+c         1
7              7  a+b+c         1

关于python - 给定 n 列的数据框,我想计算每列中特定数字的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60245422/

相关文章:

python - Django:按 child 的属性排序对象

python - 针对多个列创建列、行值映射

python - 取多个值用Python Pandas制作表格

python - 如何减少 HDFStore 的大小开销?

python - Scipy CSR "vectors"之间更快的 Python 余弦差异

python - 使用Python解压二进制文件仅返回一个值

python - 如何从第 x 行开始写入 CSV?

python - 如何从其索引和两个变量函数创建一个 pandas DataFrame?

python - 从 pandas MultiIndex 中选择列

python - 在 matplotlib 和 pandas 中组合和重新定位两个图表的图例的困难