计算数据帧中产生不同结果的行数

2024-03-29 11:11:20 发布

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

我正在将一个csv文件读入数据帧,然后我尝试计算数据帧中的行数,但得到了不同的结果。这是我的密码

data_df = pd.read_csv(data_path, header=0)
print(len(data_df.index)) # => 19695182

data_df_grouped = data_df.groupby(["SiteNumber", "WeekNumber", "PG"]).count()

data_df_grouped #-> This will print out the dataframe in jupyter notebook... I got:

enter image description here

但我接着补充说:

data_df_grouped.sum()    # And I got:

enter image description here

因此,我可以清楚地看到行数不匹配。原因可能是什么

非常感谢您的帮助


Tags: 文件csv数据path密码dfreaddata
1条回答
网友
1楼 · 发布于 2024-03-29 11:11:20

我刚刚发现我的数据帧中有重复的行,因此,上面的count后跟sum就产生了19695182行。此外,打印出len(data_df_grouped.index)将产生19573194行,因此data_df_grouped.index将返回唯一的行索引

data_df2 = data_df.drop_duplicates()
data_df2    # yielded: a dataframe with 19573194 rows × 12 columns which is what we want

相关问题 更多 >