首页 > 解决方案 > 如何在熊猫中连接两列,但通过填充南值?

问题描述

好的,所以我有两列“Price 1”和“Price 2”,“Price 1”中的一些值是 Nan,“Price 2”中的一些值是 Nan,但我想将它们连接起来。

我的代码和输出:

F3["Price 1"] = F3["Price 1"].fillna("0")
F3["Price 2"] = F3["Price 2"].fillna("0")

F3.index+=1

F3

    Price 1     Price 2
1   0        54.95
2   34.95    0
3   0        99.99
4   34.84    0
5   124.95   0
6   0        101.50

所以我希望最终是下面的这个输出:

所以最终价格中的数据将从“Price2”填充,但只有0值将填充“Price 1”

 Final Price    
1   54.95       
2   34.95   
3   99.99       
4   34.84   
5   124.95  
6   101.50  

标签: pythonpython-3.xpandasdataframepython-requests

解决方案


这可能是一个额外的步骤,但如果您想并排查看列表,最好制作一个数据框。

import pandas as pd
import numpy as np

P1 = [np.nan, 34.95, np.nan, 34.84, 124.995, np.nan]
P2 = [54.95, np.nan, 99.99, np.nan, np.nan, 101.50]

df=pd.DataFrame({'Price 1':P1 , 'Price 2' :P2})

# the answer then is to use .fillna() with price 2.
df['Price 3'] = df['Price 2'].fillna(df['Price 1'])
df

出去: 在此处输入图像描述


推荐阅读