簡體   English   中英

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

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

我想要的是為 dataframe 創建一個新列,並且該列填充有pd.Intrval(0,np.inf) ,但這樣做會導致以下錯誤:

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

重現問題的最少代碼

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

您需要指定正確的 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]

選擇:

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