Home > database >  Concat dataframes from dictionary
Concat dataframes from dictionary

Time:08-06

I have a dictionary where each key contains a dataframe column with a daterange. How can I concat all of the dictionary keys together so that I can have one dataframe with all of the columns together?

Example:

A:
              apples
2020-01-01        2
2020-01-02        3
2020-01-03        4
2020-01-04        4


B:
              bananas
2020-01-01        8
2020-01-02        10
2020-01-03        7
2020-01-04        8

C:
              carrots
2020-01-01        9
2020-01-02        2
2020-01-03        3
2020-01-04        3

New dataframe:

A:
              apples     bananas     carrots
2020-01-01        2          8           9
2020-01-02        3          10          2
2020-01-03        4          7           3
2020-01-04        4          8           3

CodePudding user response:

This would do the trick:

pd.concat(dict.values(), axis=1)

pd.concat is a fuction from pandas which adds dataframes together.

Axis = 1 tells the function that you want to add the columns.

CodePudding user response:

Something like this?

d1 = {'apples': [2, 3, 4, 4]}
d2 = {'bananas': [2, 3, 4, 4]}
d3 = {'carrots': [2, 3, 4, 4]}

df = pd.DataFrame(data = d1)
df2 = pd.DataFrame(data = d2)
df3 = pd.DataFrame(data = d3)

df = pd.concat([df, df2, df3], axis=1)
print(df)

The result is:

apples  bananas  carrots
0       2        2        2
1       3        3        3
2       4        4        4
3       4        4        4

CodePudding user response:

This could work for you,

pd.concat(dict.values())

As shown below,

>>> import pandas as pd 

# Making a dataframe 
>>> data={'Name':['Karan','Rohit','Sahil','Aryan'],'Age':[23,22,21,24]}
>>> data
{'Name': ['Karan', 'Rohit', 'Sahil', 'Aryan'], 'Age': [23, 22, 21, 24]}
>>> df=pd.DataFrame(data)
>>> df
    Name  Age
0  Karan   23
1  Rohit   22
2  Sahil   21
3  Aryan   24


# Making another dataframe
>>> data1={'Name':['Karan','Acha','Sahil','Aryan'],'Age':[29,27,21,24]}
>>> df1=pd.DataFrame(data1)
>>> df
    Name  Age
0  Karan   23
1  Rohit   22
2  Sahil   21
3  Aryan   24
>>> df1
    Name  Age
0  Karan   29
1   Acha   27
2  Sahil   21
3  Aryan   24

# Making a empty dictionary
>>> mydcit = {}
>>> mydcit
{}

# Populating the dictionary with the dataframes
>>> mydcit['A'] = df
>>> mydcit
{'A':     Name  Age
0  Karan   23
1  Rohit   22
2  Sahil   21
3  Aryan   24}

>>> mydcit['B'] = df1


# Printing the values of the dictionary
>>> mydcit.values()
dict_values([    Name  Age
0  Karan   23
1  Rohit   22
2  Sahil   21
3  Aryan   24,     Name  Age
0  Karan   29
1   Acha   27
2  Sahil   21
3  Aryan   24])

# Convering the values of the dictionary to a single  dataframe
>>> pd.concat(mydcit.values())
    Name  Age
0  Karan   23
1  Rohit   22
2  Sahil   21
3  Aryan   24
0  Karan   29
1   Acha   27
2  Sahil   21
3  Aryan   24

from here

  • Related