Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何显示该行中包含特定值的精确列_Python_Pandas_Dataframe - Fatal编程技术网

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

Python 如何显示该行中包含特定值的精确列,python,pandas,dataframe,Python,Pandas,Dataframe,所以我有一个pandasdf,它包含一组0和1 我已经有了我想要的特定行 我想显示该行中值为1的列。比如比利时队的home\u队有一个1值 我希望它看起来像: row# home_team_Belgium home_team_something 29 1 1 我可以使用什么命令?您可以执行以下操作 r = df[df.index == 29] cols_to_keep = r.iloc[0].astype(b

所以我有一个pandas
df
,它包含一组0和1

我已经有了我想要的特定行

我想显示该行中值为1的列。比如比利时队的
home\u队
有一个
1

我希望它看起来像:

row#  home_team_Belgium  home_team_something
29            1                  1            

我可以使用什么命令?

您可以执行以下操作

r = df[df.index == 29]
cols_to_keep = r.iloc[0].astype(bool).tolist()
r.iloc[:, cols_to_keep]
通常,如果要迭代所有行并打印出来,则每行中的列包含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')

随机数据帧输入:

   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

df[df.home\u team\u belling==1]@skruber,仅显示比利时。那些我不知道的有1的列呢?
row#  a  d  e
0     1  1  1

row#  c
1     1

row#  b
2     1