Python dict对象返回inf值,但它应该是数值

Python dict对象返回inf值,但它应该是数值,python,pandas,dictionary,Python,Pandas,Dictionary,已尝试应用以下代码: df = pd.read_csv('data_sample_ltv.csv') # Convert date to year date_mapper = {date: pd.to_datetime(date).year for date in df['transaction_date'].unique()} year = df['transaction_date'].map(date_mapper) df['year'] = year # Convert tier to c

已尝试应用以下代码:

df = pd.read_csv('data_sample_ltv.csv')
# Convert date to year
date_mapper = {date: pd.to_datetime(date).year for date in df['transaction_date'].unique()}
year = df['transaction_date'].map(date_mapper)
df['year'] = year
# Convert tier to categorical
tiers = pd.Categorical(df['customer_tier'],
                   categories=['Gold', 'Silver', 'Bronze', 'Free-Trial'],
                   ordered=False)
df['customer_tier'] = tiers
# Create highest tier mapper
def highest_tier(c_id, df=df):
    tier = df.loc[df.customer_id == c_id]['customer_tier'].sort_values().iloc[0]
    return tier
tier_mapper = {
    cust_id: highest_tier(cust_id) for cust_id in df['customer_id'].unique()
}
# Aggregate the data
customer_df = df.groupby(['customer_id']).agg({
    'transaction_amount': ['sum', 'count'],
    'year': [pd.Series.nunique]
})
customer_df['highest_tier'] = customer_df.index.map(tier_mapper)
customer_df['lifespan'] = customer_df[('year', 'nunique')]
customer_df['avg_trn_amt'] = customer_df[('transaction_amount', 'sum')] / customer_df[('transaction_amount', 'count')]
customer_df['avg_trn_per_yr'] = customer_df[('transaction_amount', 'count')] / customer_df['lifespan']
# Create the LTV function
def ltv(df, tier=None):
    if tier:
        df = df.loc[df['highest_tier'] == tier]
    ltv_dict = {
        'avg_lifespan': round(df['lifespan'].mean(), 1),
        'avg_trn_per_yr': round(df['avg_trn_per_yr'].mean(), 1),
        'avg_trn_amt': round(df['avg_trn_amt'].mean(), 2),
        'ltv': None
    }
    ltv_dict['ltv'] = round(
        ltv_dict['avg_lifespan'] * ltv_dict['avg_trn_per_yr'] * ltv_dict['avg_trn_amt'], 2)
    return ltv_dict
# Calculate the LTVs for each of our customer segments
ltv_all = ltv(customer_df)
ltv_gold = ltv(customer_df, 'Gold')
ltv_silver = ltv(customer_df, 'Silver')
ltv_bronze = ltv(customer_df, 'Bronze')
print(f"The lifetime value of our Gold tier is: {ltv_gold['ltv']} while the ltv of bronze is {ltv_bronze['ltv']}")
但ltv结果是inf,而不是数值:

The lifetime value of our Gold tier is: inf while the ltv of bronze is inf
每个ltv的结果均为inf:

{'avg_lifespan': 1.2, 'avg_trn_per_yr': inf, 'avg_trn_amt': 82.23, 'ltv': inf}
{'avg_lifespan': 1.1, 'avg_trn_per_yr': inf, 'avg_trn_amt': 39.9, 'ltv': inf}
{'avg_lifespan': 1.3, 'avg_trn_per_yr': inf, 'avg_trn_amt': 128.13, 'ltv': inf}
有人能帮我理解出了什么问题,我应该怎么做才能将inf转换成一个数值?谢谢。

inf
是一个数值,它是
float
对象
inf
。例如,
array([1,2,3])/0
将导致
array([inf,inf,inf])
inf
是一个数值,它是
float
对象
inf
。例如,
array([1,2,3])/0将导致
array([inf,inf,inf])