python-3.x - 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 中具有上述新索引顺序的特定第三和第四行?
解决方案
用于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
推荐阅读
- r - 如何捕获传递给函数的多个参数(...)的名称?
- python - 使用 Python 从文本表中提取数据
- python - 如何将 makefile 重写为 distutils.core.Extension
- sharepoint - 如何在 SharePoint Online 现代网站中自定义列表/库的列标题或为其设置样式?
- azure-devops - 如何防止直接推送到 AzureDevOps 中的 Master 分支
- bash - 查找和替换非 utf8 字符
- python - 在 Python / Cython / Numpy 中计算 2 个二进制向量之间的汉明距离的最快方法
- cognos - cognos analytics 11 中的上传文件位置在哪里?
- sql - 关键字“PIVOT”附近的语法不正确
- webusb - WebUSB .claimInterface 永远不会在 Windows 上返回