pandas有条件地选择多个列

时间:2017-01-02 00:37:06

标签: python pandas conditional extract multiple-columns

假设我有一个数据帧:

C1 V1 C2 V2 Cond
1  2  3  4  X  
5  6  7  8  Y  
9  10 11 12 X

语句应返回:if Cond == X, pick C1 and C2, else pick C2 and V2

输出数据框类似于:

C  V 
1  2 
7  8
9  10

**编辑:要再添加一个要求:列数可以更改,但遵循一些命名模式。在这种情况下,选择其中包含“1”的所有列,否则选择“2”。我认为硬编码的解决方案可能不起作用。

5 个答案:

答案 0 :(得分:2)

  • drop Cond专注于我从
  • 中选择的值
  • reshape numpy数组,所以我可以用布尔值区分
  • 使用np.arange(len(df))索引第一个维度,每行一次
  • 使用df.Cond.ne('X').mul(1)索引第二维。 0等于X
  • 构建最终数据框
pd.DataFrame(
    df.drop('Cond', 1).values.reshape(3, 2, 2)[
        np.arange(len(df)),
        df.Cond.ne('X').mul(1)
    ], df.index, ['C', 'V'])

   C   V
0  1   2
1  7   8
2  9  10

答案 1 :(得分:2)

我尝试使用filternumpy.where创建更通用的解决方案,因为新列名称使用extract

<Page x:Class="namespace MyAppNamespace" ...
#if necessary sort columns
df = df.sort_index(axis=1)

#filter df by 1 and 2
df1 = df.filter(like='1')
df2 = df.filter(like='2')
print (df1)
   C1  V1
0   1   2
1   5   6
2   9  10

print (df2)
   C2  V2
0   3   4
1   7   8
2  11  12

答案 2 :(得分:1)

如果行的顺序不重要,您可以使用df.locdf.append

ndf1 = df.loc[df['Cond'] == 'X', ['C1','V1']]
ndf2 = df.loc[df['Cond'] == 'Y', ['C2','V2']]
ndf1.columns = ['C','V']
ndf2.columns = ['C','V']

result = ndf1.append(ndf2).reset_index(drop=True)
print(result)
   C   V
0  1   2
1  9  10
2  7   8

答案 3 :(得分:1)

DataFrame.where()的另一个选项:

df[['C1', 'V1']].where(df.Cond == "X", df[['C2', 'V2']].values)

#  C1   V1
#0  1    2
#1  7    8
#2  9   10

答案 4 :(得分:0)

您可以尝试使用与this post

类似的方法

首先,定义几个函数:

def cond(row):
    return row['Cond'] == 'X'

def helper(row, col_if, col_ifnot):
    return row[col_if] if cond(row) else row[col_ifnot]

然后,假设您的数据框名为df

df_new = pd.DataFrame(index=df.index)
for col in ['C', 'V']:
    col_1 = col + '1'
    col_2 = col + '2'
    df_new[col] = df.apply(lambda row: helper(row, col_1, col_2), axis=1)

请记住,对于大型数据集,此方法可能会很慢,因为apply没有利用向量化。但是,它甚至可以使用任意列名称(只需将['C', 'V']替换为您的实际列名称)。