无法使用 .astype(int) 方法将 pandas 数据框列转换为 int 变量类型
Unable to convert pandas dataframe column to int variable type using .astype(int) method
我正在遍历数据帧的行以提取如下值,但我收到的始终是浮点值,我无法将 result["YEAR_TORONTO"]
和 [=15= 都转换为 int ]
for i in range(0, len(result)):
if result["SOURCE_DATASET"].iloc[i] == "toronto":
result["YEAR_TORONTO"].iloc[i] = pd.to_datetime(result["START_DATE"].iloc[i]).year
result["YEAR_TORONTO"].iloc[i].astype(int) if not np.isnan(result["YEAR_TORONTO"].iloc[i]) else np.nan
result["YEAR_TORONTO2"].iloc[i] = result["YEAR_TORONTO"].iloc[i]
知道为什么会这样吗?尝试了多种方法,包括 pd.to_numeric
和 round()
,但尽管使用了
方法,但还是没有成功
有趣的是,当我输出
result["YEAR_TORONTO"].iloc[1].astype(int) if not np.isnan(result["YEAR_TORONTO"].iloc[i]) else np.nan
,
我得到 2016
作为 int,但是一旦我通过调用 result
输出整个数据帧,我仍然得到 2016.0
作为 float
示例数据(输入):
SOURCE_DATASET START_DATE
0 brampton 06-04-16
1 toronto 06-04-16
2 brampton 06-04-16
3 toronto 06-04-99
示例数据(输出):
SOURCE_DATASET START_DATE YEAR_TORONTO YEAR_TORONTO2
0 brampton 06-04-16 NaN NaN
1 toronto 06-04-16 2016.0 2016.0
2 brampton 06-04-16 NaN NaN
3 toronto 06-04-99 1999.0 1999.0
刚刚也尝试了 np.where
,得到了相同的结果。
您使用 astype()
的方法是正确的,但如果您的列包含 nan
,它确实有效。你可以先尝试 split
result["YEAR_TORONTO"].astype(str).str.split('.', expand=True)[0].tolist()
然后分开然后从那里拿走。
或者
Result.loc[RESULT['TORONTO'].notnull(), 'x'] = result.loc[result['TORONTO'].notnull(), 'x'].apply(int)
我正在遍历数据帧的行以提取如下值,但我收到的始终是浮点值,我无法将 result["YEAR_TORONTO"]
和 [=15= 都转换为 int ]
for i in range(0, len(result)):
if result["SOURCE_DATASET"].iloc[i] == "toronto":
result["YEAR_TORONTO"].iloc[i] = pd.to_datetime(result["START_DATE"].iloc[i]).year
result["YEAR_TORONTO"].iloc[i].astype(int) if not np.isnan(result["YEAR_TORONTO"].iloc[i]) else np.nan
result["YEAR_TORONTO2"].iloc[i] = result["YEAR_TORONTO"].iloc[i]
知道为什么会这样吗?尝试了多种方法,包括 pd.to_numeric
和 round()
,但尽管使用了
有趣的是,当我输出
result["YEAR_TORONTO"].iloc[1].astype(int) if not np.isnan(result["YEAR_TORONTO"].iloc[i]) else np.nan
,
我得到 2016
作为 int,但是一旦我通过调用 result
输出整个数据帧,我仍然得到 2016.0
作为 float
示例数据(输入):
SOURCE_DATASET START_DATE
0 brampton 06-04-16
1 toronto 06-04-16
2 brampton 06-04-16
3 toronto 06-04-99
示例数据(输出):
SOURCE_DATASET START_DATE YEAR_TORONTO YEAR_TORONTO2
0 brampton 06-04-16 NaN NaN
1 toronto 06-04-16 2016.0 2016.0
2 brampton 06-04-16 NaN NaN
3 toronto 06-04-99 1999.0 1999.0
刚刚也尝试了 np.where
,得到了相同的结果。
您使用 astype()
的方法是正确的,但如果您的列包含 nan
,它确实有效。你可以先尝试 split
result["YEAR_TORONTO"].astype(str).str.split('.', expand=True)[0].tolist()
然后分开然后从那里拿走。
或者
Result.loc[RESULT['TORONTO'].notnull(), 'x'] = result.loc[result['TORONTO'].notnull(), 'x'].apply(int)