Python 迭代行并获取值组?
我有一个Python 迭代行并获取值组?,python,pandas,Python,Pandas,我有一个Df,看起来像: marker | 0 1 2 3 ________________ A | + - + - B | - - + - C | - + - - 我想在列上迭代并获得有+的行的名称,即对所有+行进行分组 我试图通过以下方式做到这一点: lis = [] for n in list(range(0,3)): cli = Df[n].tolist() for x,m in zip(cli,markers): # markers i
Df
,看起来像:
marker | 0 1 2 3
________________
A | + - + -
B | - - + -
C | - + - -
我想在列上迭代并获得有+
的行的名称,即对所有+
行进行分组
我试图通过以下方式做到这一点:
lis = []
for n in list(range(0,3)):
cli = Df[n].tolist()
for x,m in zip(cli,markers): # markers is a list of the row names ['A','B','C']
cl_li = []
if x == '+':
mset = m+x
cl_li.append(mset)
else:
continue
lis.append(cl_li)
print (lis)
但我将每行名称作为名称中自己的子列表,而我希望得到如下内容:
newdf =
____________
0 | A+
1 | C+
2 | A+B+
#n.b group 3 not included
尝试在布尔矩阵上使用
apply
和join
:
(df == '+').apply(lambda x: '+'.join(x.index[x])+'+').to_frame()
(df.index.to_series()+'+').dot((df=='+'))
输出:
0
marker
0 A+
1 C+
2 A+B+
0
marker
0 A+
1 C+
2 A+B+
或者,使用点和布尔矩阵:
(df == '+').apply(lambda x: '+'.join(x.index[x])+'+').to_frame()
(df.index.to_series()+'+').dot((df=='+'))
输出:
0
marker
0 A+
1 C+
2 A+B+
0
marker
0 A+
1 C+
2 A+B+
我的建议是使用比你更多的泛达索式解决方案 对每列应用lambda函数:
result = df.apply(lambda col: ''.join(col[col == '+'].index + '+'))
要从结果中删除空项,请运行:
result = result[result != '']
结果是:
0 A+
1 C+
2 A+B+
dtype: object
如果要将结果作为数据帧(而不是系列),请运行: