python只附加选择列作为行

2024-04-19 18:15:57 发布

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

原始文件有多列,但有很多空白,我想重新安排,以便有一个很好的信息列。从910行开始,51列(newFile df)->;想要910+x行,3列(final df)final df有910行。你知道吗

newFile sample

for i in range (0,len(newFile)):
    for j in range (0,48):
        if (pd.notnull(newFile.iloc[i,3+j])):
            final=final.append(newFile.iloc[[i],[0,1,3+j]], ignore_index=True)

我用这段代码遍历newFile,如果3+j列不为null,则将0,1,3+j列复制到新行。我尝试了append(),但它不仅添加了行,还添加了一堆带有nan的列(就像原始文件一样)。你知道吗

有什么建议吗?!你知道吗


Tags: 文件sampleingt信息dfforlen
1条回答
网友
1楼 · 发布于 2024-04-19 18:15:57

您的问题是,您使用的是数据帧并保留列名,因此添加具有值的新列将使数据帧其余部分的新列充满NaN。
另外,考虑到double-for循环,您的代码效率非常低。 下面是我使用melt()的解决方案

#creating example df
df = pd.DataFrame(numpy.random.randint(0,100,size=(100, 51)), columns=list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXY'))
#reconstructing df as long version, keeping columns from index 0 to index 3
df = df.melt(id_vars=df.columns[0:2])
#dropping the values that are null
df.dropna(subset=['value'],inplace=True)
#here if you want to keep the information about which column the value is coming from you stop here, otherwise you do 
df.drop(inplace=True,['variable'],axis=1)
print(df)

相关问题 更多 >