【问题标题】:How to multiply specific columns of a dataframe如何乘以数据框的特定列
【发布时间】:2019-08-15 10:12:46
【问题描述】:

我正在尝试将我的 pandas 数据框中的某些列乘以 100。特别是那些位于 df 中间的列。

这是我尝试在 Jupyter Notebook 中使用的代码:

quality = quality[['Question','Excellent','Above average','Average','Below the average','Very poor','Total']]

quality['Excellent','Above average','Average','Below the average','Very poor'] = quality['Excellent','Above average','Average','Below the average','Very poor']*100

quality

我预计单元格的输出应该是 0.1182 的 11.82%。

我得到的输出如下:

KeyError: ('优秀', '高于平均水平', '一般', '低于平均水平', '非常差')

【问题讨论】:

    标签: python-3.x pandas dataframe multiple-columns


    【解决方案1】:

    您需要使用双方括号来选择多列。然后你可以稍微缩短你的代码:

    quality[['Excellent','Above average','Average','Below the average','Very poor']] *= 100
    

    【讨论】:

    • 你好汤姆,谢谢你的回答,但我有一个问题:在我的 df 我有 2 列是字符串,我想保持顺序,所以如果我从上面的列创建一个 df,我会输我的顺序对吗?
    • @AngeloMerkel 不客气。随意选择它作为您接受的答案。您可以在此之后以您喜欢的任何顺序重新排序数据帧,例如:df= df[['Very Poor,'Below the average','Average','Above average','Excellent'']]
    猜你喜欢
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多