简体   繁体   English

加入 pandas Dataframe 和系列没有 NaN 值

[英]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我想加入 pandas 数据框和系列,为了更好地理解我正在采取以下示例,实际情况是有多个列,任何建议都会很明显

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 :使用DataFrame.assign ,但df2不能是系列,因为列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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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