python - 在比较之前使用插值比较两个数字 pandas 数据帧 (x,y)

标签 python pandas dataframe

我想使用 ['x1'] 比较具有不同 x 的两个数字数据帧 [x1,y1] 和 [x2,y2]

import pandas as pd
first = {'x1':[0,3,5],'y1':[0,3,6]}
df1 = pd.DataFrame(first,columns=['x1','y1'])
print (df1)
   x1   y1
0   0    0
1   3    3
2   5    6
second = {'x2':[0,2,4,6],'y2':[0,2,4,6]}
df2 = pd.DataFrame(second,columns=['x2','y2'])
print (df2)
   x2  y2
0   0   0
1   2   2
2   4   4
3   6   6

用x1值对x2进行插值,找到对应的y2。在比较 y1 和 y2 之前,我需要计算出:

   x2  y2
0   0   0
1   2   2
?   3   ?
2   4   4
?   5   ?
3   6   6

然后比较 y1 和 y2 即可发现:

   x2  y2 y1 y1>y2?
0   0   0  0
1   2   2  
?   3   3  3 False 
2   4   4
?   5   5  6 True
3   6   6

最佳答案

通过 Series.append 创建一列 DataFrame通过 Series.drop_duplicates 删除重复项并按 Series.sort_values 排序:

df = (df2['x2'].append(df1['x1'], ignore_index=True)
              .drop_duplicates()
              .sort_values()
              .to_frame('x2'))
print (df)
   x2
0   0
1   2
5   3
2   4
6   5
3   6

然后由DataFrame.merge添加y2左连接并调用 Series.interpolate ,由 Series.map 添加了新列 y1最后是比较列:

df = df.merge(df2, how='left') 
df['y2'] = df['y2'].interpolate()
df['y1'] = df['x2'].map(df1.set_index('x1')['y1'])
df['y1>y2'] = df['y1'] > df['y2']
print (df)
   x2   y2   y1  y1>y2
0   0  0.0  0.0  False
1   2  2.0  NaN  False
2   3  3.0  3.0  False
3   4  4.0  NaN  False
4   5  5.0  6.0   True
5   6  6.0  NaN  False

关于python - 在比较之前使用插值比较两个数字 pandas 数据帧 (x,y),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60361242/

相关文章:

python - 如何并行链接多个异步生成器/迭代器?

python-3.x - Pandas 系列子集索引 2 :-2 doens't work

python - 确定分组数据框中值的变化

python - 如何从数据框中找到句子中单词和字符的最大数量?

python - 计算CSV文件中每n行的平均值

python - 我的 anaconda-navigator 无法启动。(Windows 10),即使更新并重新安装后也是如此

python - 在 python 的 argparse 模块中,如何禁用大括号之间的打印子命令选择?

python - 如何使用列中的 x 轴标签在 pandas 中生成直方图?

python - 按列值中的字符串删除行

python - 多索引pandas数据框,如何获取特定索引的列表