如何使用 NaN 元素在 pandas 数据帧中执行 int 运算
How to perform int operations in pandas dataframe with NaN elements
我有一个看起来像这样的数据框:
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
是由于我逻辑中的 and
条件,但我不确定如何解决这个问题,因为NaN 值干扰并给出错误。任何帮助更正此代码的帮助都会非常有益,谢谢。
IIUC,您可以使用 to_datetime
并使用访问器 dt.year
来提取年份。然后使用 where
将不是 toronto 的行替换为 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
我有一个看起来像这样的数据框:
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
是由于我逻辑中的 and
条件,但我不确定如何解决这个问题,因为NaN 值干扰并给出错误。任何帮助更正此代码的帮助都会非常有益,谢谢。
IIUC,您可以使用 to_datetime
并使用访问器 dt.year
来提取年份。然后使用 where
将不是 toronto 的行替换为 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