Working With Comparing Dataframes And Series And Generating New Dataframes On The Fly In Python Pandas
I am creating a function that compares a dataframe (DF) to a series (S) and eventually returns a new dataframe. The common column is 'name'. I want the function to return a datafr
Solution 1:
Don, So, let's go:
# with this tables
In [66]: S
Out[66]:
0 aaa
1 bbb
2 ccc
3 ddd
4 eee
Name: name, dtype: object
In [84]: df
Out[84]:
a b c name
0 39 71 55 aaa
1 9 57 6 bbb
2 72 22 52 iii
3 68 97 81 jjj
4 30 64 78 kkk
# transform the series to a dataframe
Sd = pd.DataFrame(S)
# merge them with outer join (will keep both tables columns and values).# fill the NAs with 0
In [86]: pd.merge(Sd,df, how='outer').fillna(0)
Out[86]:
name a b c
0 aaa 39 71 55
1 bbb 9 57 6
2 ccc 0 0 0
3 ddd 0 0 0
4 eee 0 0 0
5 iii 72 22 52
6 jjj 68 97 81
7 kkk 30 64 78
is that it?
Post a Comment for "Working With Comparing Dataframes And Series And Generating New Dataframes On The Fly In Python Pandas"