python - Pandas 结合数据框

标签 python pandas

我有以下两个数据框: 第一列是索引,最后一列是通过向其附加“.txt”从索引派生的。

A
1  0.2   0.3   1.txt
2  0.4   0.6   2.txt

B
1  0.1   0.8   1.txt
2  3.0   4.5   2.txt

我想这样组合它们:

1  0.2   0.3   1.txt
2  0.4   0.6   2.txt
3  0.1   0.8   3.txt
4  3.0   4.5   4.txt

我尝试使用 pandas merge,但不确定如何在不使用 for 循环显式迭代的情况下进行操作。有什么建议吗?

最佳答案

只是concat它们作为列表并传递参数 ignore_index=true,然后将索引值分配给第 3 列,转换为 str dtype,然后附加 txt '.txt:

In [93]:

merged = pd.concat([A,B], ignore_index=True)
merged[3] = pd.Series(merged.index).astype(str) + '.txt'
merged
Out[93]:
     1    2      3
0  0.2  0.3  0.txt
1  0.4  0.6  1.txt
2  0.1  0.8  2.txt
3  3.0  4.5  3.txt

如果您坚持索引从 1 开始,您可以重新分配给它,然后运行我上面的代码:

In [100]:

merged = pd.concat([A,B], ignore_index=True)
merged.index = np.arange(1, len(merged) + 1)
merged[3] = pd.Series(index=merged.index, data=merged.index.values).astype(str) + '.txt'
merged
Out[100]:
     1    2      3
1  0.2  0.3  1.txt
2  0.4  0.6  2.txt
3  0.1  0.8  3.txt
4  3.0  4.5  4.txt

另一方面,我觉得这有点奇怪,我必须在 Series 构造函数中指定索引值才能正确对齐。

关于python - Pandas 结合数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29883922/

相关文章:

python - 我应该在 python 中输入什么样的编码声明

python - 花式索引 numpy 矩阵 : one element per row

python - 使用 Python Plotly 绘制气泡大小图例

python - Seaborn.countplot : order categories by count, 也按类别?

python - 如何使用所有 xticks 绘制 pandas 多索引数据帧

python - Pandas 通过多个正则表达式捕获组创建多个列

python - “good_new = p1[st==1]”在OpenCV中的Lucas-Kanade Optical Flow代码中意味着什么

python - master/worker 是否可扩展?

python - 使用 xlsxwriter 在条件格式(公式)后删除列

Python从pandas数据框中删除自定义停用词