合并2个不同长度的不同DataFrame
Merging 2 different DataFrame with different length
我有两个由时间和价格列组成的 DataFrame。
df1: df2:
Time1 Price1 Time2 price2
0 900 10 900 10
1 910 10 910 10
2 910 15 920 10
3 910 20 930 10
4 920 10
5 930 10
我想新建一个DataFrame df3作为df2的长度,我也想把df1['price']放在
如下所示
df3:
Time2 price2 price1
900 10 10
910 10 15
920 10 10
930 10 10
其中 price1 显示相应 time2 值的 price1 值的平均值,如下所示
import statistics
time910 = (df1.price1[1],df1.price1[2],df1.price1[3])
if df3.price1[1] = statistics.mean(time910):
print('same')
same
很抱歉,如果不清楚,但你能告诉我如何干净地完成上述操作吗?
非常感谢。
您可以尝试使用内部连接合并数据框。以下是您可以使用的逻辑!评论部分提供了更多关于代码的见解。
import pandas as pd
df_d={'Time1':[900,910,910,910,920,930],"Price1":[10,10,15,20,10,10]} # raw data as dictinary
df1=pd.DataFrame(df_d) # build a dataframe
df1_mean=df1.groupby('Time1')['Price1'].mean().to_frame() # group by Time1 and mean by price1
df2_d={'Time2':[900,910,920,930],"Price2":[10,10,10,10]} # raw data as dictinary
df2=pd.DataFrame(df2_d) # build a dataframe
现在合并将完成工作:
result=df2.merge(df1_mean,left_on='Time2',right_index=True,how='inner') # merge,right df's as key so right_index=True
我有两个由时间和价格列组成的 DataFrame。
df1: df2:
Time1 Price1 Time2 price2
0 900 10 900 10
1 910 10 910 10
2 910 15 920 10
3 910 20 930 10
4 920 10
5 930 10
我想新建一个DataFrame df3作为df2的长度,我也想把df1['price']放在 如下所示
df3:
Time2 price2 price1
900 10 10
910 10 15
920 10 10
930 10 10
其中 price1 显示相应 time2 值的 price1 值的平均值,如下所示
import statistics
time910 = (df1.price1[1],df1.price1[2],df1.price1[3])
if df3.price1[1] = statistics.mean(time910):
print('same')
same
很抱歉,如果不清楚,但你能告诉我如何干净地完成上述操作吗?
非常感谢。
您可以尝试使用内部连接合并数据框。以下是您可以使用的逻辑!评论部分提供了更多关于代码的见解。
import pandas as pd
df_d={'Time1':[900,910,910,910,920,930],"Price1":[10,10,15,20,10,10]} # raw data as dictinary
df1=pd.DataFrame(df_d) # build a dataframe
df1_mean=df1.groupby('Time1')['Price1'].mean().to_frame() # group by Time1 and mean by price1
df2_d={'Time2':[900,910,920,930],"Price2":[10,10,10,10]} # raw data as dictinary
df2=pd.DataFrame(df2_d) # build a dataframe
现在合并将完成工作:
result=df2.merge(df1_mean,left_on='Time2',right_index=True,how='inner') # merge,right df's as key so right_index=True