python - 逐行有条件地修改熊猫数据框中的列的有效方法
问题描述
我有一个看起来像这样的数据框:
length code1 code2 code3
4 0 1 1
8 1 1 0
7 1 0 0
我想编写一个检查长度值的函数。如果值 >= 7,我想将 1 添加到 code2 和 code3 中存在的值。做这个的最好方式是什么?到目前为止,我有:
def char_count_pred(df):
if df.length >= 7:
df.code2 += 1
df.code3 += 1
return df
master_df = char_count_pred(master_df)
我知道我需要构建一个循环来遍历每一行,但我对循环遍历行和在多列上执行任务的最有效方法感到困惑。
编辑
尝试以下解决方案时,我得到相同的错误:
当我按原样尝试脚本时......
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
C:\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2889 try:
-> 2890 return self._engine.get_loc(key)
2891 except KeyError:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index_class_helper.pxi in pandas._libs.index.Int64Engine._check_type()
KeyError: True
当我将脚本设置为 = 一个变量时......
File "<ipython-input-140-9f2f40a5bb96>", line 3
df = df.loc[df.length>=7]+=1
^
SyntaxError: invalid syntax
解决方案
df.loc[df.length >=7, ['code1','code2']]+=1
推荐阅读
- android - 布局在预览中很好,但在虚拟/真实设备中混乱
- c# - 在 ASP.NET MVC Web 应用程序中运行控制台应用程序
- android - Android 模拟器:在平板电脑模拟器上安装 google play 服务
- java - 快速获取 YYYYMMDD 格式的日期数的方法?
- apache-flink - Flink 部署生产标准
- javascript - 从 HTML 内容中提取平铺图像
- visual-studio-code - 如何在 VS Code 中编辑默认日志片段
- c++ - 使用向量进行 C++ 类初始化
- java - 在flyingsacer pdf中重复表格标题和thead
- ios - 在 Swift 中返回后更改对象