基于另一列提取DataFrame特定行的modelOption值
Extract
modelOption Values by typeID in Pandas Hey there! Let's break down how to pull the modelOption values you need based on typeID from your DataFrame. Here's a straightforward approach using pandas:
Step 1: Recreate Your DataFrame (for context)
First, let's make sure we're working with the same data you provided—here's how to build the DataFrame in code:
import pandas as pd # Your original data data = { 'dat': [1, 2, 3, 4, 5, 6, 7, 8], 'typeID': [2, 2, 2, 2, 1, 1, 1, 1], 'ID': [1, 2, 3, 4, 5, 6, 7, 8], 'modelOption': ['good', 'avg', 'bad', 'marginCost', 'year1Premium', 'good', 'avg', 'bad'] } df = pd.DataFrame(data)
Step 2: Extract modelOption by Specific typeID
To get only the modelOption values for a given typeID, use boolean indexing to filter rows first, then select the target column:
Example 1: Get values for typeID = 2
# Filter rows where typeID is 2, then grab modelOption type2_model_options = df[df['typeID'] == 2]['modelOption'] print(type2_model_options)
Output:
0 good 1 avg 2 bad 3 marginCost Name: modelOption, dtype: object
Example 2: Get values for typeID = 1
type1_model_options = df[df['typeID'] == 1]['modelOption'] print(type1_model_options)
Output:
5 year1Premium 6 good 7 avg 8 bad Name: modelOption, dtype: object
Step 3: Convert to a List (if needed)
If you want the results as a plain Python list instead of a pandas Series, just add .tolist():
type2_options_list = df[df['typeID'] == 2]['modelOption'].tolist() # Result: ['good', 'avg', 'bad', 'marginCost']
This method is efficient and easy to read—you first narrow down the rows that match your typeID criteria, then extract only the column you care about.
内容的提问来源于stack exchange,提问作者S31
相关产品推荐
相关产品推荐

