简体   繁体   中英

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM