简体   繁体   中英

Join pandas Dataframe and Series Without NaN values

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  |



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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM