python - 将列表的两个熊猫列相互除以
问题描述
我有一个这样的df:
col1 col2
[1,3,4,5] [3,3,6,2]
[1,4,5,5] [3,8,4,3]
[1,3,4,8] [8,3,7,2]
尝试将 col1 和 col2 中列表中的元素划分在一起以获得结果列中的内容:
col1 col2 result
[1,3,4,5] [3,3,6,2] [.33,1,.66,2.5]
[1,4,5,5] [3,8,4,3] [.33,.5,1.25,1.66]
[1,3,4,8] [8,3,7,2] [.33,1,.57,4]
尝试了很多不同的方法 - 但总是出错。
尝试:
#attempt1
df['col1'].div(df['col2'], axis=0)
#attempt2
from operator import truediv
for i in df.col1:
a = np.array(df['col1'])
for t in df.col2:
b = np.array(df['col2'])
x = a/b
print(x)
#attempt3
for i in df.index:
a = col1
b = col2
x = map(truediv, a, b)
#attempt4
a = col1
b = col2
result = [x/y for x, y in zip(a, b)]
#then apply to df
#attempt5
a = col1
b = col2
result = a/b
print(percent_matched)
#then #apply to df
>>>TypeError: unsupported operand type(s) for /: 'list' and 'list'
有任何想法吗?
解决方案
- 用于
.applymap
将列转换为np.array
s - 然后用于
.div
划分列 - 如果
result
必须四舍五入,则.apply(lambda x: np.round(x, 3))
在计算该列时添加 。np.round()
df['result'] = df.col1.div(df.col2).apply(lambda x: np.round(x, 3))
import numpy as np
import pandas as pd
data = {'col1': [[1,3,4,5], [1,4,5,5], [1,3,4,8]], 'col2': [[3,3,6,2], [3,8,4,3], [8,3,7,2]]}
df = pd.DataFrame(data)
# convert columns to arrays
df = df.applymap(np.array)
# divide the columns
df['result'] = df.col1.div(df.col2)
推荐阅读
- puppeteer - 我们可以获取之前调用的 HTTP 返回码吗?
- matlab - 求解并最小化具有多个目标的二次不等式系统
- php - 简单的字符串替换字符
- python - 有效地创建频率和新近度列
- javascript - 如何更改活动选项卡文本颜色?
- azure - 通过服务帐户的委托权限访问 Graph API,无需用户交互
- sql - 如何根据多行值选择不同的记录?
- signalr - 使用 Azure SignalR 服务的 Azure 函数开发和配置在连接字符串上引发错误消息
- python - 如何使 import speech_v1p1beta1 as speech 在谷歌云中工作?
- html - 禁用 html 或 html 和 typescript 中的按钮