Home > other >  pandas: how to create a column filled with an interval with right=np.inf?
pandas: how to create a column filled with an interval with right=np.inf?

Time:08-25

What I want is to create a new column for a dataframe, and the column is filled with a pd.Intrval(0,np.inf), but doing so will result in the following error:

IntCastingNaNError: Cannot convert non-finite values (NA or inf) to integer

Minimal code to reproduce the problem

import seaborn as sns
tips = sns.load_dataset('tips')
tips['new_col'] = pd.Interval(0,np.inf)

CodePudding user response:

You need to specify the correct dtype:

import numpy as np
tips['new_col'] = pd.Series(pd.Interval(0,np.inf),
                            dtype=pd.IntervalDtype(np.float64, 'right'),
                            index=tips.index)
tips.dtypes

total_bill                     float64
tip                            float64
sex                           category
smoker                        category
day                           category
time                          category
size                             int64
new_col       interval[float64, right]
dtype: object

tips.head()

   total_bill   tip     sex smoker  day    time  size     new_col
0       16.99  1.01  Female     No  Sun  Dinner     2  (0.0, inf]
1       10.34  1.66    Male     No  Sun  Dinner     3  (0.0, inf]
2       21.01  3.50    Male     No  Sun  Dinner     3  (0.0, inf]
3       23.68  3.31    Male     No  Sun  Dinner     2  (0.0, inf]
4       24.59  3.61  Female     No  Sun  Dinner     4  (0.0, inf]

alternative:

tips['new_col'] = pd.IntervalIndex([pd.Interval(0,np.inf)]*len(tips))
  • Related