使用df.itertuples()中的元组,如何在条件下检索每个元组元素的列值?

时间:2017-05-25 15:20:00

标签: python python-3.x pandas dataframe

我有一个pandas.DataFrame,例如:

   1  2  3
1  1  0  0
2  0  1  0
3  0  0  1

这是从包含以下关系的集合创建的:

{(1,1),(2,2),(3,3)}

我正在尝试为此制作等价类。像这样:

[1] = {1}
[2] = {2}
[3] = {3}

到目前为止,我已完成以下操作:

testGenerator = generatorTest(matrix)
indexCount = 1
while True:
    classRelation, loopCount = [], 1
    iterable = next(testGenerator)
    for i in iterable[1:]:
        if i == 1:
            classRelation.append(loopCount)
        loopCount += 1
    print ("[",indexCount,"] = ",set(classRelation))
    indexCount += 1

你可以看到它非常混乱。但我确实得到了或多或少的期望输出:

[ 1 ] =  {1}
[ 2 ] =  {2}
[ 3 ] =  {3}

如何以更整洁,更pythonic的方式完成相同的输出?

2 个答案:

答案 0 :(得分:2)

在这种情况下,您可以使用pandas.DataFrame.idxmax(),如:

<强>代码:

df.idxmax(axis=1)

测试代码:

df = pd.DataFrame([[1, 0, 0], [0, 1, 0], [0, 0, 1], [0, 1, 0]],
                  columns=[1, 2, 3], index=[1, 2, 3, 4])
print(df.idxmax(axis=1))

<强>结果:

1    1
2    2
3    3
4    2
dtype: int64

答案 1 :(得分:1)

考虑数据框<div [ngSwitch]="switchVar"> <div *ngSwitchCase="1">HTML TEXT</div> <div *ngSwitchDefault>output2</div> </div>

df

df = pd.DataFrame(np.eye(3, dtype=int), [1, 2, 3], [1, 2, 3])

numpy.where

i, j = np.where(df.values == 1) list(zip(df.index[i], df.columns[j])) [(1, 1), (2, 2), (3, 3)] stack

compress