[英]Concatenate files into one Dataframe while adding identifier for each file
所以这个问题的第一部分已经被问了很多次,我找到的最佳答案是在这里: 将多个 csv 文件导入 pandas 并连接成一个 DataFrame 文件。
但我本质上想要做的是能够为每个具有参与者编号的 dataframe 添加另一个变量,这样当文件全部连接时,我将能够拥有参与者标识符。
这些文件是这样命名的 所以也许我可以添加一个带有 ucsd1 等的列来识别每个参与者
这是我为 excel 文件工作的代码:
path = r"/Users/jamesades/desktop/Watch_data_1/Re__Personalized_MH_data_call"
all_files = glob.glob(path + "/*.xlsx")
li = []
for filename in all_files:
df = pd.read_excel(filename, index_col=None, header=0)
li.append(df)
frame = pd.concat(li, axis=0, ignore_index=True)
非常感谢!
如果我理解正确,这很简单:
import re # <-------------- Add this line
path = r"/Users/jamesades/desktop/Watch_data_1/Re__Personalized_MH_data_call"
all_files = glob.glob(path + "/*.xlsx")
li = []
for filename in all_files:
df = pd.read_excel(filename, index_col=None, header=0)
participant_number = int(re.search(r'(\d+)', filename).group(1)) # <-------------- Add this line
df['participant_number'] = participant_number # <-------------- Add this line
li.append(df)
frame = pd.concat(li, axis=0, ignore_index=True)
That way, each dataframe loaded from an Excel file will have a column called participant_number
, and the value of that column each row in each dataframe will be the number found in the filename that the dataframe was loaded from.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.