You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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.

Solution: Add ID Column Based on Numeric Value Range

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):

timestampvalueID
2018-03-19 14:31:17.20010952
2018-03-19 14:31:17.30022962
2018-03-19 14:31:17.40021472
2018-03-19 14:31:17.5003092
2018-03-19 14:31:17.6002442
2018-03-19 14:31:17.7002632
2018-03-19 14:31:17.8005482

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:07:54