在列中查找字符串,但在sam下的其他列中返回值

2024-06-17 15:09:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个df:

Car | Color | Year | Price
VW  | blue  | 2014 | 20,000
Audi| red   | 2017 | 30,000

我用如果这个表不是我真正的df,只是需要一个想法。你知道吗

我需要的车辆价格,如果选择奥迪让我们说。你知道吗

我在字符串中寻找s子字符串,但我只需要找到子字符串所在行中一个特定列的开销。你知道吗

我正在使用:

for x in cars['Car']:
   if "Audi" in x:
      #Just need the row in column 'Price'
      print(??)

Tags: 字符串indffor价格blueredcar
3条回答

您可以使用带有iterrowsfor循环来检查任何行的Car是否包含Audi。你知道吗

for index, row in cars.iterrows():
    if 'Audi' in row.Car:
        print(row.Price)

可以对pandas使用布尔索引。你知道吗

df[df['Car'].str.contains('Audi')]['Price']

要分解它:

    df['Car']                                   # Select Car column
    df['Car'].str.contains('Audi')              # Check if the value for each row contains Audi
    df[df['Car'].str.contains('Audi')]          # Select rows where contains Audi is true
    df[df['Car'].str.contains('Audi')]['Price'] # Select the price column only

不要进行字符串比较您可以直接使用pd.groupby()函数,如下所示:

import pandas as pd
import numpy as np
listt = [['VW','blue',2014,20000],
         ['Audi','red',2015,30000],
         ['BMW','black',2019,90000],
         ['Audi','white',2011,70000]]
my_df = pd.DataFrame(listt)
my_df.columns=(['Car','Color','Year','Price'])

grouped_data = my_df.groupby('Car')
grouped_data.get_group("Audi")

输出:

    Car  Color  Year  Price
1  Audi    red  2015  30000
3  Audi  white  2011  70000

相关问题 更多 >