Pandas:从多列中删除NaN并将其转换为int的最佳方法

Nik*_*ane 1 python pandas

假设我有以下CSV数据:

col1,col2,col3,label
,1,2,label1
3,,4,label2
5,6,7,label3
Run Code Online (Sandbox Code Playgroud)

读取此数据并将col1和col2转换为int的最佳方法是什么?

我能够使用并转换我的过滤数据帧,它只有数字列(col1,col2,col3).如何修改主数据框本身而忽略了作为字符串的标签列?

在相关的说明中,我也可以使用下面的命令.知道如何在循环中运行它,以便动态生成变量名col%d,因为我有32列.

filter_df.col1 = filter_df.col1.fillna(0).astype(int)
Run Code Online (Sandbox Code Playgroud)

jez*_*ael 5

使用select_dtypesnp.number:

print (filter_df)
   col1  col2  col3   label
0   NaN   1.0     2     NaN
1   3.0   NaN     4  label2
2   5.0   6.0     7  label3

cols = filter_df.select_dtypes(np.number).columns
filter_df[cols] = filter_df[cols].fillna(0).astype(int)

print (filter_df)
   col1  col2  col3   label
0     0     1     2     NaN
1     3     0     4  label2
2     5     6     7  label3
Run Code Online (Sandbox Code Playgroud)