Christian.T
Christian.T

Reputation: 17

Appending dataframe with new dataframe

I am a simple farmer who likes to pick fruit in his garden. On Monday, I picked some fruit and tracked my findings with a counter object. (I know this isn't the most efficient way to do this but bear with me):

import pandas as pd
from collections import Counter

monday = ['apple','apple','apple','orange','orange','pear','pear','banana','banana','banana','banana','banana']
mondayCount = Counter(monday)
df = pd.DataFrame.from_dict(mondayCount, orient='index').reset_index()

Out:

    index   0
0   apple   3
1   orange  2
2   pear    2
3   banana  5

I am satisfied with the outcome, and decide to do the same on the next day. Come Tuesday, I am not able to find any pears, but am able to find two pineapples:

tuesday = ['apple','orange','orange','orange','orange','banana','banana','pineapple','pineapple']

How would I then be able to append the original dataframe with the new information I've recieved on Tuesday? I am hoping to achieve an outcome similar to:

    index      0   1
0   apple      3   1
1   orange     2   4
2   pear       2   0
3   banana     5   2
4   pineapple  0   2

In the end, I would like to perform some analysis on my data after a few days of results. Would using a dataframe be the most efficient way to do this? Or is there an alternative solution that would make all of this extremely easier?

Upvotes: 0

Views: 43

Answers (2)

Pablo C
Pablo C

Reputation: 4761

You can simply create the dataframe with that data:

counters = map(Counter , [monday, tuesday])
df = pd.DataFrame(counters).T.fillna(0)

#             0    1
#apple      3.0  1.0
#orange     2.0  4.0
#pear       2.0  0.0
#banana     5.0  2.0
#pineapple  0.0  2.0

Upvotes: 0

Ferris
Ferris

Reputation: 5601

use pd.Series.value_counts to count the fruits num, and pd.concat to merge the fruits everyday.

obj_list = list()
for i in [monday, tuesday]:
    obj_list.append(pd.Series(i).value_counts())

df = pd.concat(obj_list,axis=1).fillna(0).astype(int)
print(df)

               0  1
    banana     5  2
    apple      3  1
    orange     2  4
    pear       2  0
    pineapple  0  2

Upvotes: 2

Related Questions