python - 找到一种方法来有效地执行 DataFrame 的某些列的计算
问题描述
我正在尝试查看 Pandas DataFrame 的特定列并尝试执行以下操作:
col0 col1 col2
int0 float0 str0
int1 float1 str0
int2 float2 str1
我试图在该列上逐行迭代 DataFrame,但这似乎效率不高。 Lambda 是一种选择,但我不确定 DataFrame 列是否有类似“列表理解”的东西(据我所知,这是熊猫系列)。
如果,假设 DataFrame 被定义为 df,那么我想做一些事情,比如:
for row in df:
if df['col2'] == str0:
# do some calculation for all str0 types
elif df['col2'] == str1:
# do another calculation for all str1 types
else:
# do another calculation for all other types (which are actually str2 types implied by the if-elif-else statement)
我试图重复此操作以获得一个单独的 NumPy 矩阵,该矩阵将创建一个与 DataFrame 的相应行相对应的 NumPy 行。通过检查“col2”的条件,将根据其值执行单独的计算,并生成相应 NumPy 数组的行。
请让我知道是否有有效的方法(在规范、Pythonic 编码以及时间和内存效率方面)!所有帮助将不胜感激。
解决方案
这更像是一个np.select
问题
condition = [df['col2'] == str0, df['col2'] == str1...]
Target = [function1 , function2...]
df['NewCol'] = np.select(condition , Target , default = np.nan )
推荐阅读
- xpages - 如何从 Domino 中的 URL 获取字符串查询参数
- windows - 批处理脚本中的方框图字符 (Windows CMD)
- r - 无法安装 R 包 - 系统(cmd)中的警告:找不到“make”
- .net-core - 带有 EFCore net Core 3.0 的 Dbcontext 和 Dbset
- tensorflow - 在 Colab 中保存 TensorFlow 编译模型的中断
- reactjs - 使用 react-redux-firebase 在 Firestore 中使用 React 获取参考文档
- python - 使用 Python 如何对通过音频环回发送到扬声器的所有音频进行采样
- uppaal - 检查 Mac OS Catalina 10.15 上的 Uppaal 4.1.23 是否支持 OS 错误
- postgresql - Postgres - dblink_connect 如何设置超时
- php - 如何在php laravel中按经纬度从数据库中查找特定区域?