将索引作为循环变量连接多个数据帧 [英] concat multiple dataframe with index as loop variable

查看:130
本文介绍了将索引作为循环变量连接多个数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过for循环创建多个数据帧并将它们连接起来,这很好。但我需要将循环变量包含为索引。我找不到一种方法将循环变量设置为索引

I create multiple dataframes by for loop and concat them, which works fine. But I need to include loop variable as index. I cant find a way to set loop variable as index

maindf=pd.DataFrame()
for i in ['20170724','20170725','20170726']:
    a=pd.read_csv("somecsv."+str(i))
    maindf = pd.concat(maindf,a,axis=0)

maindf的预期OP:

Expected OP for maindf:

         A  B  C
20170724 1  2  3
         4  5  6
         7  8  9
20170725 11 22 33
         44 55 66
         77 88 99
20170725 111 222 333
         444 555 666
         777 888 999


推荐答案

我认为您需要将所有 DataFrame 附加到列表然后使用 concat ,参数 keys ,也用于删除第二级添加 reset_index ,参数 drop

I think you need append all DataFrames to list and then use concat with parameter keys, also for remove second level add reset_index with parameter drop:

dfs = []
vals = ['20170724','20170725','20170726']
for i in vals:
    a=pd.read_csv("somecsv."+str(i))
    dfs.append(a)
maindf = pd.concat(dfs,keys=vals).reset_index(level=1, drop=True)

这篇关于将索引作为循环变量连接多个数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆