python - Update Dataframe column value based on other Dataframe column value
问题描述
I have a pandas Dataframe which has a couple of columns. I want to get the first 3 elements out of the Information Column based on a value in Protocol.
For example: I want the first 3 elements in Information IF the protocol is TCP.
Using below code I can separate the columns needed for my operation. But I have no clue how to adapt the next piece of code to this.
chunk[['Protocol', 'Information']] = chunk[['Protocol', 'Information']]
EDIT:
I wish to update the values. Not separate them.
解决方案
你可以使用这样的东西:
import pandas
data = data = {'Name':['first', 'second', 'third', 'fourth'],
'Age':[27, 27, 22, 32],
'Address':['New York', 'ABC', 'XYZ', 'Nowhere'],
'Qualification':['Msc', 'MA', 'MA', 'Phd']}
# Make a dataframe object
df = pandas.DataFrame(data)
# Your condition
# for example we want to get the rows with `Qualitication=='MA'
is_MA_qualified = df['Qualification'] == 'MA'
# Now to filter your data
MA_qualified = df[is_MA_qualified]
# You can use `head(n)` to get first three rows
first_three_MA_qualified = MA_qualified.head(3)
# And finally, to get any desired columns
first_three_MA_qualified[['Age','Address']]
更新:要更新单元格,您可以遍历行,然后更改满足条件的单元格的值:
...
for index, row in df.iterrows():
if row['Age'] >= 18:
df.at[index, 'Qualification'] = 'Verified'
推荐阅读
- jsf-2 - 有没有办法修复损坏的 myfaces 验证码图像?
- typescript - Visual Studio Code 中的 Typescript 错误未出现在问题列表中
- c# - 避免向控制器注入具体的数据库上下文类
- ios - Xcode 版本 10.2 在 iphone 上运行时出现问题
- node.js - 是否可以在 Node 的同一端口上运行服务器并初始化多个套接字?
- python-3.x - 文件以单一名称重复保存,不循环,不测距
- c++ - 如何修复 C++ 中向量的“下标超出范围”错误?
- apache-spark - 如何判断 Spark 使用什么 AWS 凭证来读取 S3 文件?
- php - 无法解析的依赖解析 [参数#0 [
$api_key ]] 在类 Authy\AuthyApi - javascript - 如何通过鼠标滚轮水平滚动div,锁定正文滚动?