python - 创建计算百分比重复 N 次的新列
问题描述
我想知道如何计算这些列的百分比并将其保存在旁边的新列中 N 次。例子
d1 = [['0.00', '10','11','15'], ['2.99', '30','40','0'], ['4.99', '5','0','2']]
df1 = pd.DataFrame(d1, columns = ['Price', '1','2','3'])
我希望以下操作遍历所有列(当然除了价格)
df1['1%'] = df1['1'] / df1['1'].sum() (I got an error when I tried this)
结果:
d2 = [['0.00', '10','0.22','11','0.2156','15','0.8823'], ['2.99', '30','0.66','40','0.7843','0','0'], ['4.99', '5','0.11','0','0','2','0.1176']]
df2 = pd.DataFrame(d2, columns = ['Price', '1','1%','2','2%','3','3%'])
(列可以是 N 次,所以我需要遍历所有列)
解决方案
为了获得输出,您需要使用将字符串转换为数字pd.to_numeric
pd.concat([df1, df1.drop('Price',1).apply(lambda x: pd.to_numeric(x).div(pd.to_numeric(x).sum()))
.rename(columns=lambda x: x+'%')], 1)
输出:
Price 1 2 3 1% 2% 3%
0 0.00 10 11 15 0.222222 0.215686 0.882353
1 2.99 30 40 0 0.666667 0.784314 0.000000
2 4.99 5 0 2 0.111111 0.000000 0.117647
推荐阅读
- c++ - 如何对向量中的指针进行排序但不对原始元素进行排序[C++]
- c# - C#中的变量无法从html文本框中获取值
- django - Django - 我的视图功能有什么问题?
- android - 活动结果 API(TakePicture() 相机):传递结果 ResultInfo 失败(应用程序崩溃)
- javascript - 如何在vue中修改猫头鹰轮播导航按钮?
- ruby-on-rails - Rails 切换布尔值
- javascript - 当我尝试使用“forEach”方法在数组的所有项目上插入 onclick 事件时,为什么“innerHTML”不起作用?
- microsoft-graph-api - 通过来自 microsoft graph 的 messageId 获取电子邮件
- python - 为什么我会遇到这个简单的 If 循环错误?
- python - 请求触发时,FastAPI 流式响应为空