gpt4 book ai didi

python - 有没有办法将谷歌云存储中的 csv 文件中的数据加载到 datalab 中的单独变量中?

转载 作者:行者123 更新时间:2023-12-01 06:47:35 25 4
gpt4 key购买 nike

我曾经使用 Jupyter Notebook 访问本地目录中的 CSV 文件中的数据,但是,现在我想通过 datalab 访问存储在 Google 云存储中的 CSV 文件。这是我用来运行该函数的部分:

def function1(file_name):
new_file = open("file_name.csv", "w")
new_file.write("variable"+'\n')
with open(file_name, "r") as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
values_in_column1 = int(row[0])
variable = values_in_column1 * 0.6 / 5

如何更改此函数以使其能够与存储在 google cloiud 存储和 datalab 中的 CSV 文件一起使用?

Datalab 使我能够将 csv 文件的数据加载到一个变量中,但我不想将所有数据加载到一个变量中。我想将每列的值加载到不同的变量中。

%%gcs read --object gs://bucket-name/file_name.csv --variable variable_name

有人推荐使用字典或列表吗?或者有更简单的方法来做到这一点吗?

我尝试使用来自 google.cloud 的存储,但在通过终端更新 Google 云存储时无法导入它。

ImportErrorTraceback (most recent call last)
<ipython-input-6-943e66fe7e46> in <module>()
----> 1 from google.cloud import storage
2
3 storage_client = storage.Client()
4 bucket = storage_client.get_bucket(bucket_name)
5 blob = bucket.blob(source_blob_name)

ImportError: cannot import name storage

最佳答案

  1. 我创建了一个笔记本实例 link .

  2. 我将 csv 文件复制到 Google Cloud Storage。

        gsutil cp file.csv gs://my-bucket/
  3. 然后使用 pandas:

        import pandas as pd

    df = pd.read_csv('gs://my-bucket/file.csv')

    df

    # cdatetime address district beat grid crimedescr ucr_ncic_code latitude longitude
    # 0 1/1/06 0:00 3108 OCCIDENTAL DR 3 3C 1115 10851(A)VC TAKE VEH W/O OWNER 2404 38.550420 -121.391416
    # 1 1/1/06 0:00 2082 EXPEDITION WAY 5 5A 1512 459 PC BURGLARY RESIDENCE 2204 38.473501 -121.490186

    # You can access now the columns of the dataframe

    df['district']

    #0 3
    #1 5
    #2 2
    #3 6
    #4 2

    df['variable'] = df['district'] * 0.6 / 5

    #0 0.36
    #1 0.60
    #2 0.24
    #3 0.72
    #4 0.24

关于python - 有没有办法将谷歌云存储中的 csv 文件中的数据加载到 datalab 中的单独变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59159824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com