python - 如何在熊猫中连接两列,但通过填充南值?
问题描述
好的,所以我有两列“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
解决方案
这可能是一个额外的步骤,但如果您想并排查看列表,最好制作一个数据框。
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
推荐阅读
- google-chrome-extension - 未捕获的类型错误:无法从 chrome.storage.get() 读取属性“已检查”的 null
- reactjs - 收到错误“输入是一个无效元素标签,既不能有‘children’也不能使用‘dangerouslySetInnerHTML’”
- java - 如何在 localhost 上正确使用 Dropbox api?
- r - 合并具有不相等行且没有匹配列名的数据框 R
- floating-point - 为什么 PowerPC 的 stfs 指令没有按预期运行?
- excel - 有没有办法创建一个循环通过一组代码循环然后在下一个循环中偏移某个数字
- groovy - 在任意位置处理 spock 特征方法中的资源
- sql-server - 在 SQL Server Management Studio 2016 中设置双向关系
- java - 如何从java上的socket读取多种类型的数据
- reactjs - Sematic UI 在 react nextjs projet 中覆盖引导页面样式