Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用NaN元素在dataframe中执行int操作_Python_Pandas_Numpy_Dataframe_Nan - Fatal编程技术网

Python 如何使用NaN元素在dataframe中执行int操作

Python 如何使用NaN元素在dataframe中执行int操作,python,pandas,numpy,dataframe,nan,Python,Pandas,Numpy,Dataframe,Nan,我有一个数据框,看起来像: Brand Price 0 toronto 16-Aug-16 1 quebec 18-May-17 2 brampton 18-May-17 3 toronto 31-Dec-97 我目前的代码如下: df["YEAR_TORONTO"] = np.nan df["YEAR_TORONTO"] = np.where(df["Brand"] == "toron

我有一个数据框,看起来像:

    Brand    Price
0   toronto  16-Aug-16
1   quebec   18-May-17
2   brampton 18-May-17
3   toronto  31-Dec-97
我目前的代码如下:

df["YEAR_TORONTO"] = np.nan
df["YEAR_TORONTO"] = np.where(df["Brand"] == "toronto", df["Price"], np.nan)
df["YEAR_TORONTO"] = df["YEAR_TORONTO"].str[-2:]
df["YEAR_TORONTO"] = np.where(isinstance(df["YEAR_TORONTO"], str) and df["YEAR_TORONTO"].astype(int) >= 20, "19" + df["YEAR_TORONTO"], "20" + df["YEAR_TORONTO"])
df["YEAR_TORONTO"] = df["YEAR_TORONTO"].fillna(0).astype(int).astype(object).where(df["YEAR_TORONTO"].notnull())
这给了我一个如下的结果:

    Brand    Price       YEAR_TORONTO
0   toronto  16-Aug-16   2016
1   quebec   18-May-17   NaN
2   brampton 18-May-17   NaN
3   toronto  31-Dec-97   2097

我知道
2097
而不是
1997
是由于我的逻辑中的
条件造成的,但我不确定如何解决这一问题,因为NaN值干扰并给出错误。任何更正此代码的帮助都将非常有益,谢谢。

IIUC,您可以使用
来更新时间
并使用访问器
dt.year
来提取年份。然后使用
where
将非多伦多的行替换为
pd.NA
以保持年份为整数

df["YEAR_TORONTO"] = (pd.to_datetime(df['Price']).dt.year
                        .where(df['Brand'].eq('toronto'), pd.NA))
print(df)
      Brand      Price YEAR_TORONTO
0   toronto  16-Aug-16         2016
1    quebec  18-May-17         <NA>
2  brampton  18-May-17         <NA>
3   toronto  31-Dec-97         1997
df[“YEAR\u TORONTO”]=(pd.to\u datetime(df['Price']).dt.YEAR
.其中(df[‘品牌’].eq(‘多伦多’),pd.NA))
打印(df)
多伦多品牌价格年
0多伦多2016年8月16日
1魁北克2017年5月18日
2017年5月18日,布兰普顿2号
3多伦多1997年12月31日

谢谢,这是另一种选择