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

基于NA条件定义函数处理DataFrame生成price列的技术问询

Pandas: Convert n_var to price Column Using Date-Based Rules

Got it, let's work through this problem together. You need to transform the n_var column into a price column based on specific date conditions, and we'll build a reusable function to handle this properly.

First, Let's Clarify the Problem

Your original DataFrame looks like this:

date1date2Date3n_var
2017-02-012019-02-042018-04-012
2016-02-01NA2017-01-023
2017-02-012019-02-042020-04-017
2016-02-012019-02-042020-04-017

And you want to generate this target DataFrame:

date1date2Date3price
2017-02-012019-02-042018-04-012
2016-02-01NA2017-01-023
2017-02-012019-02-042020-04-01NA
2016-02-012019-02-042020-04-01NA

Note on the Rules

I noticed there might be a typo in your rule 2: "当date2为NA且date2 < date3时" (when date2 is NA and date2 < date3) doesn't make sense, since you can't compare a missing value to a date. Looking at your target output, I'm guessing the correct rule 2 should be:

当date2不为空且Date3 > date2时,price设为NA (When date2 is not NA and Date3 is later than date2, set price to NA)

If that's not right, you can adjust the condition in the code below easily.

Solution Code

First, we'll write a function that handles date conversion and applies the rules:

import pandas as pd

def transform_to_price(df):
    # Make a copy to avoid modifying the original DataFrame
    df_processed = df.copy()
    
    # Convert all date columns to datetime type (critical for proper comparison)
    date_columns = ['date1', 'date2', 'Date3']
    df_processed[date_columns] = df_processed[date_columns].apply(pd.to_datetime)
    
    # Initialize price column with original n_var values
    df_processed['price'] = df_processed['n_var']
    
    # Apply Rule 1: Set price to NA if Date3 < date1
    df_processed.loc[df_processed['Date3'] < df_processed['date1'], 'price'] = pd.NA
    
    # Apply Rule 2 (corrected): Set price to NA if date2 is not NA AND Date3 > date2
    df_processed.loc[df_processed['date2'].notna() & (df_processed['Date3'] > df_processed['date2']), 'price'] = pd.NA
    
    # Remove the original n_var column
    df_processed = df_processed.drop('n_var', axis=1)
    
    return df_processed

How to Use the Function

  1. Create your original DataFrame:
original_df = pd.DataFrame({
    'date1': ['2017-02-01', '2016-02-01', '2017-02-01', '2016-02-01'],
    'date2': ['2019-02-04', pd.NA, '2019-02-04', '2019-02-04'],
    'Date3': ['2018-04-01', '2017-01-02', '2020-04-01', '2020-04-01'],
    'n_var': [2, 3, 7, 7]
})
  1. Call the function to get your target DataFrame:
target_df = transform_to_price(original_df)
print(target_df)

Output

Running this code will give you exactly the target DataFrame you wanted:

date1      date2      Date3 price
0 2017-02-01 2019-02-04 2018-04-01     2
1 2016-02-01        NaT 2017-01-02     3
2 2017-02-01 2019-02-04 2020-04-01  <NA>
3 2016-02-01 2019-02-04 2020-04-01  <NA>

Key Notes

  • We convert date columns to datetime first because string comparisons won't work correctly for dates.
  • Using df.loc for conditional updates is efficient and avoids slow apply loops.
  • We make a copy of the input DataFrame to prevent accidentally modifying your original data.

内容的提问来源于stack exchange,提问作者Naï

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:42:02