python - 根据两个标准从数据框中提取数据
问题描述
给出以下示例。
d = {'col1': [1, 2, 3], 'col2': [6, 7]}
df = pd.DataFrame(data=d)
df
col1 col2
0 1 6
1 2 7
newdf[df['col1' ==2]
newdf
col1 col2
0 2 7
适用于单色
但
newdf[df['col1' ==2 & 'col2' == 7]
我赢得了错误奖。
解决方案
以下都不正确
newdf[df['col1' ==2]
newdf[df['col1' ==2 & 'col2' == 7]
newdf[df['col1' == 2 && 'col2' == 7]
括号必须围绕每个条件
- Pandas:布尔索引
import pandas as pd
d = {'col1': [1, 2, 3, 2], 'col2': [6, 7, 8, 9]}
df = pd.DataFrame(data=d)
col1 col2
0 1 6
1 2 7
2 3 8
3 2 9
# specify multiple conditions
newdf = df[(df.col1 == 2) & (df.col2 == 7)]
print(newdf)
col1 col2
1 2 7
推荐阅读
- heroku-cli - when pushing to heroku and getting an error
- python - Python 计算 gotos 和 USE_COMPUTED_GOTOS?
- web-scraping - Scraping Data on TradingView with BeautifulSoup
- html - How can I horizontally center grid items that have been wrapped onto a new row
- php - Creating zipped file of many pdfs automatically
- android - snapHelper.findSnapView() 总是返回 null
- bash - 将第二个参数传递给 Bash 函数
- image-processing - 如何提高训练和测试的准确性
- c++ - std::destroy 是基本类型的无操作吗?
- linq - linq 组消息仅显示最后的消息,就像应用程序所做的那样