python - 将列转换为行并在python中打印与其相邻的值和值计数

标签 python pandas

我已将 csv 导入到我的 python 代码中,如下所示:

df = pd.DataFrame({
         50001:[np.nan,5,np.nan,5,5,np.nan],
         50002:[np.nan,np.nan,9,np.nan,np.nan,3],
         50003:[np.nan,3,5,np.nan,1,np.nan],

})

我希望我的数据如下所示:

enter image description here

我已经为此编写了代码,但我只得到分数和值。我无法获取rule_id 列。这是我正在使用的代码:

for i in dframe:
    dframe1 = dframe.loc[: , i].value_counts()
    print(dframe1)

这给了我这样的结果:

enter image description here

如果您能帮我解决这个问题,我将不胜感激。

最佳答案

使用DataFrame.meltSeriesGroupBy.value_countsGroupBy.size :

df = (df.melt(var_name='Rule_ID', value_name='Score')
        .groupby('Rule_ID')['Score']
        .value_counts()
        .reset_index(name='Value_Count'))
print (df)
   Rule_ID  Score  Value_Count
0    50001    5.0            3
1    50002    3.0            1
2    50002    9.0            1
3    50003    1.0            1
4    50003    3.0            1
5    50003    5.0            1

或者:

df = (df.melt(var_name='Rule_ID', value_name='Score')
        .groupby(['Rule_ID', 'Score'])
        .size()
        .reset_index(name='Value_Count'))

关于python - 将列转换为行并在python中打印与其相邻的值和值计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55238650/

相关文章:

python - Python for循环简单数组

python - 使用电子邮件验证用户帐户 (Google App Engine)

python - 如何在python中实现n次嵌套循环?

python - 在 python 中读取 CSV 时双引号中的换行符

python - 将 Pandas Data Frame 放入现有 Excel 工作表

python - 获取列表中随机数据帧的索引位置

python - 由于插入命令中的单引号而导致 psycopg2 语法错误

python - 您可以在python中创建图形(线性,饼图,条形图),但使用从mysql获取的数据吗?

python - iloc方法返回不同类型的数据

excel - 使用for循环(Python)追加/连接多个excel数据集