python-2.7 - Pandas:如何获得一个新的数据框,其中填充了 2 个或 3 个或 X 个其他数据框的并集?

标签 python-2.7 pandas ipython dataframe

我有一个很长的数据框,每天的日期从 1999 年开始。我对 original_dataframe 应用一个过滤器来创建一个 new_dataframe_1 和另一个过滤器来创建 new_dataframe_2。

如何创建仅包含 new_dataframe_1 和 new_dataframe_2 共有的行的第三个数据帧?

new_dataframe_1

    A   B   C   D
1   a   b   c   d
2   a   b   c   d
3   a   b   c   d
4   a   b   c   d


new_dataframe_2

    A   B   C   D
3   a   b   c   d
4   a   b   c   d
5   a   b   c   d
6   a   b   c   d


new_dataframe_3 = union of new_dataframe_1 and new_dataframe_2


    A   B   C   D
3   a   b   c   d
4   a   b   c   d

最佳答案

如果您希望将两个 DataFrame 中的列连接在一起,请执行内部连接:

import pandas as pd

df1 = pd.DataFrame({'A': range(5)}, index=list('abcde'))
df2 = pd.DataFrame({'B': range(10,20,2)}, index=list('AbCdE'))

print(df1)
#    A
# a  0
# b  1
# c  2
# d  3
# e  4

print(df2)
#     B
# A  10
# b  12
# C  14
# d  16
# E  18

print(df1.join(df2, how='inner'))

产量
   A   B
b  1  12
d  3  16

如果您只想从 DataFrame 之一中选择列,
做一个 reindex在索引的交集上:
import pandas as pd

df1 = pd.DataFrame({'A': range(5)}, index=list('abcde'))
df2 = pd.DataFrame({'A': range(5)}, index=list('AbCdE'))
print(df1)
#    A
# a  0
# b  1
# c  2
# d  3
# e  4

print(df2)
#    A
# A  0
# b  1
# C  2
# d  3
# E  4

print(df1.reindex(df1.index.intersection(df2.index)))

产量
   A
b  1
d  3

还有df1.locdf1.ix ,但是 df1.reindex似乎更快:
In [33]: idx1 = df1.index    
In [34]: idx2 = df2.index

In [35]: %timeit df1.loc[idx1.intersection(idx2)]
1000 loops, best of 3: 269 µs per loop

In [36]: %timeit df1.ix[idx1.intersection(idx2)]
1000 loops, best of 3: 276 µs per loop

In [37]: %timeit df1.reindex(idx1.intersection(idx2))
10000 loops, best of 3: 186 µs per loop

关于python-2.7 - Pandas:如何获得一个新的数据框,其中填充了 2 个或 3 个或 X 个其他数据框的并集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19410629/

相关文章:

python - 如何使用 python 2.7 获取发送和接收的总字节数?

Python pandas从一列字符串的数据选择中过滤掉nan

python - 在 Ubuntu 中编译 Python 2.6.6 并需要外部包 wxPython、setuptools 等...

python - ipython并行和非复制发送numpy数组

python - 曲线拟合分段函数?

python - 如何动态地为 Python 中的类属性赋值?

python - 在 Jinja2 模板中使用 utf-8 字符

python - 是否可以使用 pandas.melt() 将列交换为列的元素?

python - 对某些列中的 pandas 数据帧进行平均

django - 在/admin/配置不当