python-3.x - 如何在 Python 中的多索引列中连接满足特定条件的 Pandas 数据框

标签 python-3.x pandas dataframe

我有以下两个数据框:

d1 = {('CAR','ALPHA'): pd.Series(['A11', 'A12', 'A13', 'A14'],index=[1, 2, 3, 4]),
      ('CAR','BETA'): pd.Series(['B11', 'B12', 'B13', 'B14'],index=[1, 2, 3, 4])}
da= pd.DataFrame(data=d1)
d2 = {('CAR','ALPHA'): pd.Series(['A22', 'A23', 'A24', 'A25'],index=[2, 3, 4, 5]), 
      ('CAR','BETA'): pd.Series(['B22', 'B23', 'B24', 'B25'],index=[2, 3, 4, 5]),
      ('MOTOR','SOLO'): pd.Series(['S22', 'S23', 'S24', 'S25'], index=[2, 3, 4, 5])}
db= pd.DataFrame(data=d2)

它们应该看起来像这样:

enter image description here

我想要实现的是添加一个新的数据帧,两个数据帧的所有列在其中一个列索引中具有特定单词。

例如,我希望所有在顶部列级别具有 CAR 的列:

enter image description here

我的 pandas 版本是 0.21.0,我的复杂版本代码中的列名称如下:

df = pd.concat([da, db], axis=1)
print(df.columns)
Index([('V', 'C', 'I', 'P'),
       ('V', 'G', 'T', '-'),
       ('P', 'G', 'T', '-')], dtype='object')

在上面,我只想保留列多重索引第一级中带有 V 的列。

提前致谢。

最佳答案

使用pandas.concatDataFrame.xs :

df = pd.concat([da, db], axis=1).xs('CAR', level=0, axis=1, drop_level=False)

或者使用slicers :

df = pd.concat([da, db], axis=1).loc[:, pd.IndexSlice['CAR', :]]

print (df)
    CAR                
  ALPHA BETA ALPHA BETA
1   A11  B11   NaN  NaN
2   A12  B12   A22  B22
3   A13  B13   A23  B23
4   A14  B14   A24  B24
5   NaN  NaN   A25  B25

编辑:

DataFrame有4个级别,所以需要:

idx = pd.Index([('V', 'C', 'I', 'P'),
       ('V', 'G', 'T', '-'),
       ('P', 'G', 'T', '-')], dtype='object')
df = pd.DataFrame(0, columns=idx, index=[1,2])
print (df)
   V     P
   C  G  G
   I  T  T
   P  -  -
1  0  0  0
2  0  0  0


df1 = df.xs('V', level=0, axis=1, drop_level=False)
print (df1)
   V   
   C  G
   I  T
   P  -
1  0  0
2  0  0

为每个级别添加:以选择第二,第三和第四级别的所有值:

df1 = df.loc[:, pd.IndexSlice['V', :, :, :]]
print (df1)
   V   
   C  G
   I  T
   P  -
1  0  0
2  0  0

关于python-3.x - 如何在 Python 中的多索引列中连接满足特定条件的 Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54423470/

相关文章:

php - 将数据从 PHP(客户端)传输到 Python 脚本(服务器)

python - 修改描述函数以删除和添加列

python - 无法腌制 redis-py 实例 (_thread.lock)

python - 使用 GroupBy 查找 DataFrame 中的最小值

python-3.x - 在python中将OpenCV对象保存在内存中

python - 重新排列 python pandas 数据框(部分转置)

python - pandas.DataFrame.shift() fill_value 不工作

python - 计算 pandas 中数据框中每一列的值变化,忽略 NaN 变化

python - pyspark在某些条件下选择窗口上的第一个元素

python - 我可以检查 pandas dataframe 索引是否结束?