I want to join the pandas data frame and series, to understand better i am taking the following example, the real scenario is having multiple columns any suggestions would be appreciable
import pandas as pd
data = [[1,2],[2,3],[3,4]]
df1 = pd.DataFrame(data, columns=['A',"B"])
print(df1)
dict = {'C': 5,
'D': 6}
# create series from dictionary
s1 = pd.Series(dict)
print(s1)
Data Frame : DF1
| A | B |
| ----|-----|
| 1 | 2 |
| 2 | 3 |
| 3 | 4 |
Pandas Series : S1
| C | 5 |
| D | 6 |
Data Frame : Result
| A | B | C | D |
| ----|-----|-----|-----|
| 1 | 2 | 5 | 6 |
| 2 | 3 | 5 | 6 |
| 3 | 4 | 5 | 6 |
CodePudding user response:
Use DataFrame.assign
, but df2
cannot be Series, because column name
:
df = df1.assign(**df2.loc[0])
print (df)
A B C
0 1 2 5
1 2 3 5
2 3 4 5
Or if input is dictionary use:
d = {'C': 5,'D': 6}
df = df1.assign(**d)