Home>

I want to concatenate dataframe with a for statement.

user_dct = {100: "Tom", 101: "Jon", 102: "Daisy"}
for key, value in user_dct.items ():
        "File = '. /' + Value + '. Csv'
    Df = pd.read_csv (file)
I wrote

and the code.

For df,

Date ID Name Score Rank
0 2011-01-12 100 Tom 40 C
1 2011-01-14 100 Tom 60 B
2 2011-01-19 100 Tom 80 A
・
・
・</Code></pre>
<pre><code>Date ID Name Score Rank
0 2011-01-12 101 Jon 30 C
1 2011-01-14 101 Jon 50 C
2 2011-01-19 101 Jon 60 B
・
・
・</Code></pre>
<p><br />
It is like this.<br />
After concatenation,</p>
<pre><code>Name Score Rank
    Date ID
2011-01-12 100 Tom 40 C
        101 Jon 30 C
        102 Daisy 90 S
2011-01-14 100 Tom 60 B
        101 Jon 50 C
            102 Daisy 90 S
2011-01-19 100 Tom 80 A
        101 Jon 60 B
        102 Daisy 80 A
・
・
・</Code></pre>
<p><br />
I want to format like this. Pivot table format</p>
<pre><code>df = df.pivot_table (index = ['Date', 'ID'])


I think it will be like that if you write
I don't know how to make a df before that.
I think that data frames can be linked with pd.concat, but how should they be linked in this case?

  • Answer # 1

    Isn't this ok?

    user_dct = {100: "Tom", 101: "Jon", 102: "Daisy"}
    dfs = []
    for key, value in user_dct.items ():
        file = './'+value+'.csv'
        dfs.append (pd.read_csv (file, parse_dates = ['Date']))
    df = pd.concat (dfs, ignore_index = True)
    print (df)