python - 转换遍历行的函数以应用方法 pandas
问题描述
我有一个函数,我在数据帧的行上一个接一个地运行。我想以某种方式将其转换为 pandas apply 方法或类似方法,并希望能够提高性能。
所以数据框看起来像这样:
df
object_id ... param_dict
8804 15563 ... {81: 2.0}
8805 15566 ... {81: 2.0}
8806 15553 ... {81: 2.0}
8808 15531 ... {81: 2.0}
8811 15639 ... {81: 2.0}
... ... ... ...
16525 1158 ... {4: 9963.302345992126, 46: 92.4}
16526 1156 ... {4: -0.0, 46: 67.5}
16527 1089 ... {4: -0.0, 46: 76}
16528 898 ... {4: -0.0, 46: 67.5}
16531 893 ... {4: -0.0, 46: 67.5}
[1333 rows x 8 columns]
和功能:
def function(df):
# running over the index of the dataframe
for index in df.index:
# running over the keys of the dataframe['param_dict'] dictionaries
for key in df['param_dict'][index]:
if df['param_dict'][index][key] == 0:
continue
if key in [4, 27]:
print(df['name'][index], df['param_dict'][index][key], 1)
elif key in [46, 28, 29]:
print(df['name'][index], df['param_dict'][index][key], 2)
else:
print(df['name'][index], df['param_dict'][index][key], 3)
return None
所以目前,第一个 for 循环运行了 1333 次,并且根据字典的键,内部 for 循环也运行了几次。有没有办法以某种方式将此函数转换为应用方法,这样至少我不需要遍历索引?
这是简单的数据集:
df = pd.DataFrame({'name': ['a', 'b', 'c'], 'param_dict': [{4: 0, 1: 4}, {46: True}, {35: False, 25: 0}]})
解决方案
您可以创建一个应用于 pandas 数据帧中每一行的函数,修改该行并将其新版本返回给 df,例如:
def func(row):
row['key1'] = row['key1'] + row['key2']
return row
然后你可以将它应用到索引上:
df = df.apply(func, axis=1)
推荐阅读
- javascript - RESCO OfflineHtml:无法调试 Javascript 代码
- flutter - 在颤动中使用 AlertDialog 从数据库中显示选定的数据
- visual-studio - 将 Visual Studio 连接到远程 Docker 卷
- python - 如何定义根据 CXYPY 中的变量改变值的参数
- neo4j - Cypher 查询中的 UNWIND 语句
- css - 背景大小不适用于普通类是否需要任何解决方法
- javascript - 如何拥有多个带有上一个、下一个和添加图标的 HTML5 画布
- mysql - Ansible 访问因“root@localhost”错误而被拒绝
- c++ - 旋转矩阵并删除字符并找到最大的正方形
- docker - 如何更改/升级 Docker 映像的一部分?图像内的模块,而不是整个图像