对于循环,通过具有相同标头的目录中的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循环垂直组合列。我想学习如何像在excel中那样水平执行此操作
而不是包含所有数据的A列和B列。我希望每个文件的列A B彼此相邻,以便有列A B C D E F G
抱歉,我不懂编码术语。如果国防部发现这一点,请在必要时重新措辞
谢谢
您可以在循环外部创建一个空df,然后沿每个循环的列连续连接:
相关问题 更多 >
编程相关推荐