如何显示该行中包含特定值的确切列

时间:2018-07-05 02:59:56

标签: python pandas dataframe

所以我有一个熊猫df,其中包含一堆0和1。

并且我已经有想要的特定行

enter image description here

我想显示该行的值为1的列。就像home_team_Belgium的值为1一样。

我希望它看起来像:

row#  home_team_Belgium  home_team_something
29            1                  1            

我可以使用哪些命令?

2 个答案:

答案 0 :(得分:0)

您可以做类似的事情

r = df[df.index == 29]
cols_to_keep = r.iloc[0].astype(bool).tolist()
r.iloc[:, cols_to_keep]

答案 1 :(得分:0)

row = df.loc[29]
row = row[row == 1]
row = row.to_frame().T
row.columns.name = 'row#'
print(row)

通常,如果要遍历所有行并打印出每一行包含1的列:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.choice([0, 1], size=(3, 5)), columns=list('abcde'))
# To iterate over all rows. You can also select specific rows with `index`
for index, row in df.iterrows():
    # To select target cols you want in each row.
    output = row[row == 1]
    # To print each result row horizontally.
    output = output.to_frame().T
    # Make header row exactly in your expected format.
    output.columns.name = 'row#'
    print(output, end='\n\n')

随机DataFrame输入:

   a  b  c  d  e
0  1  0  0  1  1
1  0  0  1  0  0
2  0  1  0  0  0

打印输出:

row#  a  d  e
0     1  1  1

row#  c
1     1

row#  b
2     1
相关问题