我正在尝试使用以下代码行将 DataFrame (df
) 上传到云存储:
bucket.blob(gcs_reference).upload_from_string(df.to_csv(index=False, encoding='utf-8'), content_type=''application/octet-stream')
但是,我的 DataFrame 对于某些单元格没有值,因此它会触发错误:
ValueError: None could not be converted to unicode
有没有办法抑制这种情况,只为 None 放置空值?我过去没有遇到任何问题,我不记得我做了什么不同的事情。
最佳答案
我能够重现并且它对我有用:
import pandas as pd
from gcloud import storage
client = storage.Client()
bucket = client.get_bucket('source')
d = {'col1': [1, 2], 'col2': [3, None]}
df = pd.DataFrame(data=d)
bucket.blob('file').upload_from_string(df.to_csv(index=False, encoding='utf-8'),
content_type='application/octet-stream')
文件内容为:
col1,col2
1,3.0
2,
或者您可以使用:
df.fillna(value=0, inplace=True)
bucket.blob('file').upload_from_string(df.to_csv(index=False,
encoding='utf-8'), content_type='application/octet-stream')
输出文件为:
col1,col2
1,3.0
2,0.0
在您的代码中是这部分:
content_type=''application/octet-stream'
这是一个语法错误
content_type=''application/octet-stream'
关于python - Bucket.blob.upload_from_string 返回 "ValueError: None could not be converted to unicode",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58747610/