python - 如何使用应用于数据框迭代行?
问题描述
我想使用 apply 方法迭代行。第一行“1”是一个带有句子的字符串,其余行是浮点数。我将把这些行用在一个函数中。像这样的东西:
def my_function(row1, row2, row3, row4):
if row["1"]:
'''do some stuff here with the rows'''
return # the dataframe with the modification to the float rows "2" "3" "4"
df['row1'] = df['row1'].apply(lambda row: my_function(row['row1'], row['row2'], row['row3'], row['row4']))
TypeError: string indices must be integers
一个例子:第一行是一个句子,如果句子中有任何“a”,那么我们继续修改浮点行,函数将返回最后三行的修改。
解决方案
您需要声明轴,因为默认情况下apply
沿列应用函数。另一方面,你应该决定你的函数是使用一行作为参数还是单个元素,老实说我更喜欢第一个。你的代码可能是这样的:你需要这个:
def my_function(row):
if row["a"] ... :
# do something
if row["b"] ... :
# do something
return something
df_negative['new_a'] = df_negative['a'].apply(my_function, axis=1) # without lambda function
推荐阅读
- javascript - JS:日期操作
- operating-system - 如何在微型 RTOS 中实现调度程序,该调度程序能够在任务超时时中断任务
- file - Symfony 3 上传文件 - FileNotFoundException
- windows - 如何在 VS 代码任务中获取时间戳?
- sql - MSSQL - 如果第一次返回 0,则运行第二次选择
- sql - 在同一个表中链接行是一种不好的模式吗?
- node.js - 我可以在没有 docker 的 Windows Server 上运行 Puppeteer.js 刮板吗?
- java - 更新到 Android Studio 3.2.1 后无法解析模块依赖
- javascript - 如何在 CKEditor 5 的自定义元素中插入带有标题的图像?
- regex - 在 Python 中使用正则表达式检测凌乱文本中的段落边界