Led*_*Led 3 python nan dataframe pandas
在 DataFrane.to_csv 中,我设法编写了删除nan值的csv 文件
df = df.replace('None','')
df = df.replace('nan','')
Run Code Online (Sandbox Code Playgroud)
但我的问题是,使用这种方法,每个 nan 值都将被替换为 qoutes: ''
是否可以根据类型替换 nan 值?
if the nan dataframe == int dont add qoutes
if str set to ''
if float set to 0.0
Run Code Online (Sandbox Code Playgroud)
等等。
试过这个代码但失败了
df['myStringColumn'].replace('None', '')
Run Code Online (Sandbox Code Playgroud)
编辑:这是我拥有的示例数据框
aTest Vendor name price qty
0 y NewVend 21.20 nan
1 y OldMakes 11.20 3
2 nan nan sample 9.20 1
3 n nan make nan 0
Run Code Online (Sandbox Code Playgroud)
这是我的目标
'y','NewVend','',21.20,,
'y','OldMakes','',11.20,3,
'','','sample',9.20,1,
'n','','make',0.0,0,
Run Code Online (Sandbox Code Playgroud)
这是完整的脚本
dtype_dic= {'price': float, 'qty': float}
df = pd.read_excel(os.path.join(sys.path[0], d.get('csv')), dtype=str)
for col, col_type in dtype_dic.items():
df[col] = df[col].astype(col_type)
df = df.replace('None','')
df = df.replace('nan','')
df.to_csv('test.csv', index=False, header=False, quotechar='"', quoting=csv.QUOTE_NONNUMERIC)
Run Code Online (Sandbox Code Playgroud)
Vai*_*ali 11
您可以使用 select_dtypes 选择具有所需类型的列,然后使用 fillna 如果 nan 是 np.nan,它也适用于 None
float_cols = df.select_dtypes(include=['float64']).columns
str_cols = df.select_dtypes(include=['object']).columns
df.loc[:, float_cols] = df.loc[:, float_cols].fillna(0)
df.loc[:, str_cols] = df.loc[:, str_cols].fillna('')
Run Code Online (Sandbox Code Playgroud)
你得到
aTest Vendor name price qty
0 y NewVend 21.2 0.0
1 y OldMakes 11.2 3.0
2 sample 9.2 1.0
3 n make 0.0 0.0
Run Code Online (Sandbox Code Playgroud)