【问题标题】:How to concat two columns in pandas,but by filling the Nan Value?如何在熊猫中连接两列,但通过填充南值?
【发布时间】:2021-03-13 12:25:34
【问题描述】:

好的,所以我有两列“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

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

因此最终价格中的数据将从“价格2”填充,但只有0值将填充到“价格1”中

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

【问题讨论】:

  • 如果您的数据是相同的模式,那么您可以添加两个价格,即F3['Final Price']=F3["Price 1"]+F3["Price 2"]
  • df['Final Price'] = df.sum(axis=1)??
  • 它只能 concat str 而不是 float 是我得到的错误
  • 我假设你在做连接之前做了 fillna
  • 是的,我已经完成了填充 na,因为它们之前是“Nan”值,我只是将它们设为 0。

标签: python python-3.x pandas dataframe python-requests


【解决方案1】:

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

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

输出:

【讨论】:

    【解决方案2】:
    df = pd.DataFrame({'Price 1' : [0,34.95,None,34.84,124.95 ,None ],
                       'Price 2' : [54.95,None,54.95,None,None ,101.50 ]
                      })
    
    df = df.fillna(0)
    
    df['Final Price'] = df.apply(lambda row: row['Price 2'] if row['Price 1'] == 0 else row['Price 1'],
                         axis=1)
    

    【讨论】:

    • 尽量避免申请,因为它很慢。
    • 嗨,我厌倦了您的公式,但最终价格列与“价格 1”列相同,没有任何变化。 0 值尚未填充 :(
    • 在运行 lambda 行之前是否使用了 fillna(0)?
    【解决方案3】:
    F3 = F3.fillna(0)
    F3['Final price'] = F3['Price 1'].where(F3['Price 1'] != 0, F3['Price 2'])
    

    或者不填充 Nans:

    F3['Final price'] = F3['Price 1'].where(~F3['Price 1'].isnull(), F3['Price 2'])
    

    根据:pd.Series.where()

    【讨论】:

    • 与评论中发布的答案有何不同?
    • 我可能是在别人评论的时候打字的。道歉。
    • 嗨,我也厌倦了这个公式,但最终价格列与“价格 1”列相同,没有任何变化。 0 值尚未填充 :(
    • 这样写:F3['Price 1'] = F3['Price 1'].astype(float) and F3['Price 2'] = F3['Price 2'].astype(浮动)在公式之前。您已将数据读取为字符串。
    【解决方案4】:

    感谢大家的帮助,但我终于通过先将其转换为浮点值然后将它们相加来解决它

    F1["Price 1"] = F1["Price 1"].fillna("0").astype(float)
    F1["Price 2"] = F1["Price 2"].fillna("0").astype(float)
    
    F1['Final Price'] = F1.apply(lambda x: x['Price 1'] + x['Price 2'], axis=1)
    

    【讨论】:

    • 您填写的是字符串而不是整数。 do fillna(0) 通过引入字符串,您将浮点列更改为对象类型
    猜你喜欢
    • 1970-01-01
    • 2021-03-18
    • 2019-01-05
    • 1970-01-01
    • 2019-08-17
    • 2021-03-10
    • 1970-01-01
    • 2021-10-04
    • 2021-09-28
    相关资源
    最近更新 更多