首页 > 解决方案 > Python Pandas 在特定索引上合并来自不同 Dataframe 的数据并创建新的

问题描述

我的代码如下:我有两个数据框a,b。我想通过合并a、b帧的特定索引数据来创建一个新的数据帧c。

import pandas as pd
a = [10,20,30,40,50,60]
b = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6]
a = pd.DataFrame(a,columns=['Voltage'])
b = pd.DataFrame(b,columns=['Current'])
c = pd.merge(a,b,left_index=True, right_index=True)
print(c)

实际输出为:

     Voltage  Current
0       10      0.1
1       20      0.2
2       30      0.3
3       40      0.4
4       50      0.5
5       60      0.6

我不想要所有的行。但是,特定的索引行类似于:

c =      Voltage Current
     0     30      0.3
     1     40      0.4

如何修改c = pd.merge(a,b,left_index=True, right_index=True)代码,以便我只想要 c 中具有上述新索引顺序的特定第三和第四行?

标签: python-3.xpandasdataframe

解决方案


用于iloc按位置选择行并在两者中添加reset_index默认drop=True索引DataFrames

解决方案1 concat

c = pd.concat([a.iloc[2:4].reset_index(drop=True),
               b.iloc[2:4].reset_index(drop=True)], axis=1)

或使用merge

c = pd.merge(a.iloc[2:4].reset_index(drop=True),
             b.iloc[2:4].reset_index(drop=True), 
             left_index=True, 
             right_index=True)

print(c)
   Voltage  Current
0       30      0.3
1       40      0.4

推荐阅读