Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
93 views
in Technique[技术] by (71.8m points)

python - 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?

question from:https://stackoverflow.com/questions/65877883/appending-dataframe-with-new-dataframe

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...