假设我有一个数据文件:
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”的其他列。我认为硬编码的解决方案可能行不通。
发布于 2017-01-02 08:31:11
我尝试用filter和numpy.where创建更通用的解决方案,对于新列名使用extract
#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#np.where need same shape of mask as df1 and df2
mask = pd.concat([df.Cond == 'X']*len(df1.columns), axis=1)
print (mask)
Cond Cond
0 True True
1 False False
2 True True
cols = df1.columns.str.extract('([A-Za-z])', expand=False)
print (cols)
Index(['C', 'V'], dtype='object')
print (np.where(mask, df1,df2))
Index(['C', 'V'], dtype='object')
[[ 1 2]
[ 7 8]
[ 9 10]]
print (pd.DataFrame(np.where(mask, df1, df2), index=df.index, columns=cols))
C V
0 1 2
1 7 8
2 9 10发布于 2017-01-02 01:47:32
DataFrame.where()的另一种选择
df[['C1', 'V1']].where(df.Cond == "X", df[['C2', 'V2']].values)
# C1 V1
#0 1 2
#1 7 8
#2 9 10发布于 2017-01-02 00:56:12
drop Cond专注于我从中选择的值reshape numpy数组,这样我就可以用布尔值进行区分。np.arange(len(df))索引第一维度,每一行一次df.Cond.ne('X').mul(1)索引二维。0等于Xpd.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 10https://stackoverflow.com/questions/41420264
复制相似问题