gpt4 book ai didi

python - Panda 0.22 dataframe.drop 比它应该多的行

转载 作者:太空宇宙 更新时间:2023-11-04 04:49:30 26 4
gpt4 key购买 nike

从两个文件中加载两个数据帧(testdf和datadf)然后使用

df = pd.concat([testdf,datadf])到目前为止,生成的 df.shape 为 (48842,15)。

现在我需要 80% 的训练,10% 的测试,10% 的验证

trndf = df.sample(frac=0.8)返回正确的形状 (39074,15)。

tmpdf = df.drop(trndf.index)现在这里的想法是从 df 数据帧中删除那些 39074 行,总共应该留下 9768。但是 tmpdf 数据帧形状是 (4514, 15) 丢失 5254 行。

df 使用默认索引,编号从 0 到 48841 如下示例

idx 年龄工类
0 25 私有(private)
1 28 私有(private)

下面的 trndf dataframe 样本是随机样本,我确认索引号与 df dataframe 中的索引匹配

idx 年龄工类
228 25 ?
2164 35 州政府

对它如何设法丢失这些额外行的想法持开放态度。感谢对此的任何见解。谢谢

最佳答案

默认情况下 pd.concat 不会重置索引,因此如果索引同时存在于 testdfdatadf 中,它们当这些指数被抽样时,它们都会同时被丢弃。

drop 将删除所有重复的索引,因此您会从存在于 testdfdatadf 中的索引中丢失更多行。

潜在的解决方案正在将 df = pd.concat([testdf,datadf]) 更改为

df = pd.concat([testdf,datadf]).reset_index()

df = pd.concat([testdf,datadf], ignore_index=True)

问题重现:

df = pd.DataFrame({'a': {0: 0.6987303529918656,
1: -1.4637804486869905,
2: 0.4512092453413682,
3: 0.03898323021771516,
4: -0.143758037238284,
5: -1.6277278110578157}})

df_combined = pd.concat([df, df])
print(df_combined)
print(df_combined.shape)
sample = df_combined.sample(frac=0.5)
print(sample.shape)
df_combined.drop(sample.index).shape

a
0 0.698730
1 -1.463780
2 0.451209
3 0.038983
4 -0.143758
5 -1.627728
0 0.698730
1 -1.463780
2 0.451209
3 0.038983
4 -0.143758
5 -1.627728
(12, 1) # print(df_combined.shape)
(6, 1) # print(sample.shape)
Out[37]:
(4, 1) # df_combined.drop(sample.index).shape

关于python - Panda 0.22 dataframe.drop 比它应该多的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48717245/

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