我有一个3000+列的数据框.数据框中的许多单元格都是空字符串('').此外,我有很多数字值是字符串,但实际上应该是整数.我写了两个函数用0填充所有空单元格,并在可能的情况下将值更改为整数,但是当我运行它们时,我的数据帧没有任何变化.功能:
def recode_empty_cells(dataframe, list_of_columns):
for column in list_of_columns:
dataframe[column].replace(r'\s+', np.nan, regex=True)
dataframe[column].fillna(0)
return dataframe
def change_string_to_int(dataframe, list_of_columns):
dataframe = recode_empty_cells(dataframe, list_of_columns)
for column in list_of_columns:
try:
dataframe[column] = dataframe[column].astype(int)
except ValueError:
pass
return dataframe
Run Code Online (Sandbox Code Playgroud)
注意:我正在使用try/except语句,因为某些列包含某种形式的文本.在此先感谢您的帮助.
编辑:
感谢您的帮助,我得到了第一部分工作.现在所有空单元都有0.这是我此时的代码:
def recode_empty_cells(dataframe, list_of_columns):
for column in list_of_columns:
dataframe[column] = dataframe[column].replace(r'\s+', 0, regex=True)
return dataframe
def change_string_to_int(dataframe, list_of_columns):
dataframe = recode_empty_cells(dataframe, list_of_columns)
for column in list_of_columns:
try:
dataframe[column] = dataframe[column].astype(int)
except ValueError:
pass
return dataframe
Run Code Online (Sandbox Code Playgroud)
但是,这给了我以下错误: OverflowError: Python int too large to convert to C long
你没有保存你的功能变化:
def recode_empty_cells(dataframe, list_of_columns):
for column in list_of_columns:
dataframe[column] = dataframe[column].replace(r'\s+', np.nan, regex=True)
dataframe[column] = dataframe[column].fillna(0)
return dataframe
Run Code Online (Sandbox Code Playgroud)