我目前在一个文件夹中有多个csv文件,每个文件具有以下结构:
第一栏,第二栏
x1,y1
x2,y2
...
其中所有csv文件中的第1列均相同。我正在尝试将第1列的文件夹中的所有csv文件加入其中,并在输出csv中标识每个第2列的来源,请通过其文件名重命名新列(column2)。我想知道是否有办法在python中完成它?
如果我正确理解了您的问题,那么应该可以解决您的问题:
import pandas as pd
import os
df = pd.DataFrame()
for filename in os.listdir(dir_name):
if filename.endswith('.csv'):
curr_df = pd.read_csv(os.path.join(dir_name, filename))
# In case this is the first df, then add the common column
if df.empty:
column1_header = list(curr_df.columns)[0]
df[column1_header] = curr_df[column1_header]
df[filename] = curr_df.iloc[:, 1]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句