首页 > 解决方案 > 从 Python 中的现有列创建新列

问题描述

我在 Python 中有以下名为“final”的数据框

购买日期 截止日期 is_trial_period 当前的日期
2013 年 10 月 12 日。 2013-12-12 错误的 2021 年 10 月 6 日。
2013-10-12 2013-12-12 错误的 2021 年 10 月 6 日。
2021-10-04 2021-11-04。 真的 2021 年 10 月 6 日。

最终数据帧的数据类型是+

purchase_date:datetime64[ns]
,Expiration_date:datetime64[ns]
,is_trial_period:object
,current_date:datetime64[ns],
dtype: object

我想创建一个名为 XYZ 的新列。

  1. 如果 is_trail_period 为 FALSE 且 Expiration_date >= current_date,则 XYZ 列的值应为“Active Subscription”,否则为“Expired Subscription”
  2. 如果 is_trail_period 为 TRUE 且 Expiration_date >= current_date,则 XYZ 列的值应为“Active TRIAL”,否则为“Expired TRIAL”

我怎么能在 Python 中做到这一点?

我试着做

def func(row):
    if ((bool(final['is_trial_period'])== 'FALSE') & (final['Expiration_date'] >= final['current_date'])):
        return 'Active Subscription'
    elif ((bool(final['is_trial_period'])== 'FALSE') & (final['Expiration_date'] < final['current_date'])):
        return 'Expired Subscription'
    elif ((bool(final['is_trial_period'])== 'TRUE') & (final['Expiration_date'] >= final['current_date'])):
        return 'Active Trial'
    elif ((bool(final['is_trial_period'])== 'FALSE') & (final['Expiration_date'] < final['current_date'])):
        return 'Expired Trial'

final['XYZ'] = final.apply(func, axis=1)

但随后我收到错误“ValueError:系列的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。”

我希望我的最终输出像

购买日期 截止日期 is_trial_period 当前的日期。 XYZ
2013-10-12 2013-12-12 错误的 2021-10-0 过期订阅
2013-10-12 2013-12-12 错误的 2021-10-06 过期订阅
2021-10-04 2021-11-04 真的 2021-10-06 主动试用

标签: python

解决方案


你应该打电话row而不是final. 同时删除不必要bool的转换,一切准备就绪。

尝试这个:

import pandas as pd


data = {
    'purchase_date': ['2013-10-12', '2013-10-12', '2021-10-04'],
    'expiration_date': ['2013-12-12', '2013-12-12', '2021-11-04'],
    'is_trial_period': ['FALSE', 'FALSE', 'TRUE'],
    'current_date': ['2021-10-06', '2021-10-06', '2021-10-06']
}

def func(row):
    if row['is_trial_period'] == 'FALSE' and row['expiration_date'] >= row['current_date']:
        return 'Active Subscription'
    elif row['is_trial_period'] == 'FALSE' and row['expiration_date'] < row['current_date']:
        return 'Expired Subscription'
    elif row['is_trial_period']== 'TRUE' and row['expiration_date'] >= row['current_date']:
        return 'Active Trial'
    elif row['is_trial_period'] == 'FALSE' and row['expiration_date'] < row['current_date']:
        return 'Expired Trial'

final = pd.DataFrame(data)
final['XYZ'] = final.apply(func, axis=1)

print(final)

输出:

  purchase_date expiration_date is_trial_period current_date                   XYZ
0    2013-10-12      2013-12-12           FALSE   2021-10-06  Expired Subscription
1    2013-10-12      2013-12-12           FALSE   2021-10-06  Expired Subscription
2    2021-10-04      2021-11-04            TRUE   2021-10-06          Active Trial

推荐阅读