如何在DataFrame中添加ID列?按数值区间分配对应ID值
Hey there! Let's tackle this problem step by step. You want to add an ID column to your DataFrame where IDs are set to 1 if the numeric value falls between 0 and 100, and 2 otherwise. I'll walk you through how to do this using pandas (the standard library for DataFrames in Python), including handling your provided sample data.
First, let's turn your sample data into a proper pandas DataFrame. Here's the code to replicate your dataset:
import pandas as pd import numpy as np # Your sample data converted into a dictionary sample_data = { 'timestamp': [ '2018-03-19 14:31:17.200', '2018-03-19 14:31:17.300', '2018-03-19 14:31:17.400', '2018-03-19 14:31:17.500', '2018-03-19 14:31:17.600', '2018-03-19 14:31:17.700', '2018-03-19 14:31:17.800' ], 'value': [1095, 2296, 2147, 309, 244, 263, 548] } # Create the DataFrame df = pd.DataFrame(sample_data) # Optional (but recommended): Convert timestamp to datetime type df['timestamp'] = pd.to_datetime(df['timestamp'])
Now, let's add the ID column using two common methods—pick the one that fits your workflow best:
Method 1: Using numpy.where() (Fastest for Large Datasets)
This is the most efficient approach, especially if you're working with big data. It vectorizes the condition check instead of processing rows one by one:
# Add ID column: 1 if value is 0-100, else 2 df['ID'] = np.where((df['value'] >= 0) & (df['value'] <= 100), 1, 2)
Method 2: Using pandas.apply() (More Explicit for Simple Logic)
If you prefer a readable, row-by-row approach (great for small datasets or when you need to expand logic later), use apply:
def get_id(row): if 0 <= row['value'] <= 100: return 1 else: return 2 df['ID'] = df.apply(get_id, axis=1)
Final Result
After running either method, your DataFrame will look like this (note all sample values are above 100, so all IDs are 2):
| timestamp | value | ID |
|---|---|---|
| 2018-03-19 14:31:17.200 | 1095 | 2 |
| 2018-03-19 14:31:17.300 | 2296 | 2 |
| 2018-03-19 14:31:17.400 | 2147 | 2 |
| 2018-03-19 14:31:17.500 | 309 | 2 |
| 2018-03-19 14:31:17.600 | 244 | 2 |
| 2018-03-19 14:31:17.700 | 263 | 2 |
| 2018-03-19 14:31:17.800 | 548 | 2 |
Quick tip: If you need to adjust the range (like excluding 0 or 100), just tweak the condition in either method—super easy to modify!
内容的提问来源于stack exchange,提问作者Maphanew Kim

