图纸数据框变为与构造的相同数据框不相等

2024-05-19 02:09:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要这方面的帮助,因为我已经搜索了近3个小时的解决方案,但没有找到任何东西

我在这里有一个简单的pandas数据框,它是从脚本创建的,这个数据框通过使用Google Sheet API上传到google工作表

源代码:

import gspread, pandas as pd

cols = [
"Filename",
"Version Number",
"House Name",
]

df = pd.DataFrame(columns=cols)

for i in range(0,5):
    out = {
    "Filename":i,
    "Version Number":i+1,
    "House Name":i+2
    }
    df = df.append(out,ignore_index=True)





creds_path = "creds.json"
service_account = gspread.service_account(filename=creds_path)
spreadsheet = service_account.open_by_key("1a8NxVF6yUE0jSa63tjhEDHAS2q7dsdo0lT4saMGKROI")
worksheet = spreadsheet.sheet1


df2 = pd.DataFrame(worksheet.get_all_records())
print(df.equals(df2))

#worksheet.clear()
#worksheet.update([df.columns.values.tolist()] + df.values.tolist())

这是一个非常简单的脚本,它创建了一个pandas数据帧,然后以编程方式将其上传到googlesheet。我制作这张表是为了测试目的,我可以公开给任何人,如果你想试用,你需要.json文件,其中包含凭据,我也为任何想试用的人制作了一份,但请注意,这是仅用于测试目的

Note: I will be deactivating credentials once the question is answered.

链接:

现在我有个问题。一旦创建了pandas数据帧,然后将其与这部分代码一起上载worksheet.clear()&worksheet.update([df.columns.values.tolist()] + df.values.tolist())。您可以在工作表上清楚地看到它的工作原理,工作表如下所示

sheet image

现在,当我尝试读取该工作表并使用以下命令将其转换为pandas数据帧时

df2 = pd.DataFrame(worksheet.get_all_records())

我只是想看看工作表上的数据是否与脚本上创建的数据框完全相同。现在,当我运行这个print(df.equals(df2))时,它返回False,这意味着dfdf2不同dataframe,我可以清楚地看到不是我所期望的。原因很明显,我上传了相同的数据帧,但为什么在比较这两个数据帧时它会说False?事实上它应该在哪里True对吗

如果您试图打印出df&df2你可以清楚地看到他们是一样的,对吗?我建议你试着自己把剧本打印出来

df

  Filename Version Number House Name
0        0              1          2
1        1              2          3
2        2              3          4
3        3              4          5
4        4              5          6

df2

   Filename  Version Number  House Name
0         0               1           2
1         1               2           3
2         2               3           4
3         3               4           5
4         4               5           6

主要目标:

My objective is just to see if the data from the sheet is exactly the same as the created dataframe in the script. I just wanted to like to check if they are the same cause I would be doing other stuffs depending on that condition.

有没有人能教育我,让我知道我在这里缺少了什么。非常感谢你的帮助


Tags: the数据namenumberpandasdfversionfilename
1条回答
网友
1楼 · 发布于 2024-05-19 02:09:19

gspread API返回类型为int64的数据帧df2,而您手动创建的数据帧df的类型为int。由于类型不同,两个数据帧不相等

如果您尝试df.astype('int64').equals(df2),它将返回True

或者,您可以使用all(df.eq(df2)),它也将返回True。这将比较数据帧的每个元素,并使用all组合布尔标志

第三种方法(OP在下面的评论中建议)是做df.astype("str").equals(df2.astype("str"))

相关问题 更多 >

    热门问题