python - Bucket.blob.upload_from_string 返回 "ValueError: None could not be converted to unicode"

标签 python google-cloud-platform google-cloud-storage

我正在尝试使用以下代码行将 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/

相关文章:

Python - 只提取第一个数字

bash - 如何重置 Google Cloud Shell 用户永久磁盘?

object - "Live object"中的 "Object Lifecycle Management"是什么?

google-app-engine - 在 OS X 下的 PyCharm 上运行 GAE GCS,运行时错误 "No module named cloudstorage"

python - 从 GCS 获取大量 csv 文件到 BQ

python - 如何从另一个 Python 脚本调用特定的 Scrapy 蜘蛛

python - 0. 在 Python 中是什么意思?

python - pyserial,导入错误 : No module named serial

google-cloud-platform - YouTube 的 Google OAuth 验证品牌

hadoop - 在 GCP 上连接 b/w R studio server pro 和 hive