gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:20:55 25 4
gpt4 key购买 nike

我想使用 ['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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com