对于循环,通过具有相同标题的目录中的csv文件进行解析,并在每个循环文件之后打印新列



循环通过具有相同标题的目录中的csv文件进行解析,并在每个循环文件后打印新列

正如下面的代码所示,它垂直地组合了一个目录中的所有文件。我希望它在每个文件后水平组合,以具有多行

import os
import pandas as pd
#RUN THIS AFTER MAKING ALL THE CSV FILEs
dfmaster = pd.DataFrame()
directory = "/content/drive/My Drive/"
for filename in os.listdir(directory):
fullpath = os.path.join(directory, filename)
if os.path.isfile(fullpath) and fullpath.endswith(".csv"):
dfchild = pd.read_csv(fullpath)
select_cols = ['var1', 'var2']
#define columns you want to explort
dfmaster = dfchild[select_cols]
#####Problem here, After each file print to two new columns I don't know what to input here
print(dfmaster.reset_index(drop=True))
dfmaster.to_csv("/content/drive/My Drive/Subsurface_A.csv", index=False)

所以总结:当前的for循环垂直组合列。我想学习如何水平地做这件事,就好像这是一个出色的

而不是具有所有数据的列A、B。我希望每个文件的列A B放在一起,这样就有了列A B C D E F G…

抱歉,我不懂编码术语。如果国防部看到这一点,请在必要时重新措辞。

谢谢!

您可以在循环外创建一个空的df,然后在每个循环中沿着列连续连接:

#empty df
finaldf = pd.Dataframe()
for filename in os.listdir(directory):
fullpath = os.path.join(directory, filename)
if os.path.isfile(fullpath) and fullpath.endswith(".csv"):
dfchild = pd.read_csv(fullpath)
select_cols = ['obs', 'temperature']
#define columns you want to explort
dfmaster = dfchild[select_cols]
#new line
finaldf = pd.concat([finaldf, dfmaster],axis = 1)

print(finaldf.reset_index(drop=True))
finaldf.to_csv("/content/drive/My Drive/Subsurface_A.csv", index=False)

最新更新