社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

使用python根据条件提取数据

disukumo • 3 年前 • 1120 次点击  

我有以下数据帧(df):

科鲁阿 上校B 上校
123 A. 1Q
124 B L1
125 B QW
126 A. E2

如果用户选择了特定的列和值,则整行应保存为新的数据帧。例如,如果用户选择Col_A 123,则输出应如下所示:

科鲁阿 上校B 上校
123 A. 1Q

如果用户选择Col_B:B和Col_A:125,则输出应符合以下要求:

科鲁阿 上校B 上校
125 B QW

如果用户选择Col_B:B,则输出应如下所示:

科鲁阿 上校B 上校
124 B L1
125 B QW

我该怎么做?

到目前为止我试过什么?


import pandas as pd
import numpy as np
df= pd.read_csv('Table.csv')
print('Enter the value as 99 if the Col_A or Col_B is not known')
Col_A_value= (input(str("Enter tag of your interest separated by ',': ")).split(","))
Col_B_value= (input(str("Enter iris_image_id of your interest separated by ',': ")).split(","))
input_table = []
for i,j in itertools.product(Col_A_value, Col_B_value):
    if len(i) > 0 and len(j)==0:
        input_table.append(df[df['Col_A'] == i])
    elif i != '99' and len(j)> 0:
        input_table.append(df[df['Col_A'] == i]) 

如果指定了Col_a和Col_B,则上述脚本不会提取特定数据。如果我指定Col_A=124和Col_B=B,那么所有结果都是Col_B。

期望输出:

科鲁阿 上校B 上校
124 B L1
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130884
 
1120 次点击  
文章 [ 2 ]  |  最新文章 3 年前
Fareed Khan
Reply   •   1 楼
Fareed Khan    3 年前
# Importing Libraries
import pandas as pd

# Importing dataframe
df = pd.read_csv('mydata.csv')


# Col A Value input as int
first_input = int(input('Enter Col A Value'))

# Col B value input as string
second_input = str(input('Enter Col B Value'))

# checking both column values with == sign 
df[(df['Col_A'] == first_input) & (df['Col_B']== second_input)]
yhn
Reply   •   2 楼
yhn    3 年前

你可以试试这个:

import pandas as pd
d = {'col1': [1, 2], 'col2': [3, 4], 'col3': [3, 4]}
df = pd.DataFrame(data=d)
print(df)
print(df[(df['col1']==1) & (df['col2']==3)])

结果: enter image description here

-----------或者--------

尝试在以下位置使用熊猫功能:( link to pandas.where tuto ),使用函数比使用循环更好