简体   繁体   English

pandas:如何创建一个用 right=np.inf 填充的列?

[英]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:我想要的是为 dataframe 创建一个新列,并且该列填充有pd.Intrval(0,np.inf) ,但这样做会导致以下错误:

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:您需要指定正确的 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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