如何在 python 中用 NaN 替换空序列值
how to replace empty series values with NaN in python
我正在迭代多个列并将它们的摘要统计信息(如均值、中位数、偏度和峰度)存储在如下字典中:
metrics_dict['skewness'] = data_col.skew().values[0]
metrics_dict['kurtosis'] = data_col.kurt().values[0]
metrics_dict['mean'] = np.mean(data_col)[0]
metrics_dict['median'] = np.median(data_col)
但是对于某些列,它给出如下错误:
IndexError: index out of bounds
有问题的列如下:
Index device
61021 C:2
61022 D:3+
61023 D:3+
61024 B:1
61025 D:3+
61026 C:2
我只是想将 NA 附加到 dict 中以防出现这样的列,而不是让错误中断我的循环。这里的index只是dataframe的索引,操作的column是device。请注意,数据有大量数字列(~500),其中 2 -3 列就像设备,因此我只需要将 NA 添加到字典中,然后转到下一列。
有人可以告诉我如何在 python 中做到这一点吗?
Select 数据框中要将空值设置为 nan 的列。
df[df['col'] == ''] = np.nan
希望对您有所帮助。
您可以尝试使用 try/except IndexError
try:
# whatever you do that might rise an IndexError
except IndexError:
# append NA to dict
由于这些统计信息仅对数字列有意义,您可以尝试隔离数字列。这可以使用 pd.DataFrame.select_dtypes
:
numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
numeric_cols = df.select_dtypes(include=numerics).columns
for col in df:
if col in numeric_cols:
# calculate & add some values to dictionary
else:
# add NA values to dictionary
我正在迭代多个列并将它们的摘要统计信息(如均值、中位数、偏度和峰度)存储在如下字典中:
metrics_dict['skewness'] = data_col.skew().values[0]
metrics_dict['kurtosis'] = data_col.kurt().values[0]
metrics_dict['mean'] = np.mean(data_col)[0]
metrics_dict['median'] = np.median(data_col)
但是对于某些列,它给出如下错误:
IndexError: index out of bounds
有问题的列如下:
Index device
61021 C:2
61022 D:3+
61023 D:3+
61024 B:1
61025 D:3+
61026 C:2
我只是想将 NA 附加到 dict 中以防出现这样的列,而不是让错误中断我的循环。这里的index只是dataframe的索引,操作的column是device。请注意,数据有大量数字列(~500),其中 2 -3 列就像设备,因此我只需要将 NA 添加到字典中,然后转到下一列。 有人可以告诉我如何在 python 中做到这一点吗?
Select 数据框中要将空值设置为 nan 的列。
df[df['col'] == ''] = np.nan
希望对您有所帮助。
您可以尝试使用 try/except IndexError
try:
# whatever you do that might rise an IndexError
except IndexError:
# append NA to dict
由于这些统计信息仅对数字列有意义,您可以尝试隔离数字列。这可以使用 pd.DataFrame.select_dtypes
:
numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
numeric_cols = df.select_dtypes(include=numerics).columns
for col in df:
if col in numeric_cols:
# calculate & add some values to dictionary
else:
# add NA values to dictionary