python - 如果第一行为 0,则从 DataFrame 中选择列

标签 python pandas

我试图将数据帧(df)的所有列选择到一个新的数据帧中,其中第一行的值为 ==0。

df=

   a  b  c  d
0  1  0  3  0
1  2  7  2  2
2  3  5  2  1

new_df:

     b   d
0    0   0
1    7   2
2    5   1

这感觉像是一项简单的任务,但我完全陷入寻找有效的东西。提前致谢!

最佳答案

首先使用DataFrame.loc with : 按条件选择所有行和列 - 比较第一行:

df1 = df.loc[:, df.iloc[0] == 0]

或者将行与label=0进行比较,显然也是首先:

df1 = df.loc[:, df.loc[0].eq(0)]

print (df1)
   b  d
0  0  0
1  7  2
2  5  1

关于python - 如果第一行为 0,则从 DataFrame 中选择列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69102966/

相关文章:

python - 在 python 子进程 check_output 中使用绝对路径的任何方式

python - python中几天的累计总和

python - 使用 python 从配置单元读取数据时出现性能问题

python - Treeview如何使用光标上下键选择多行

python - 如何创建在 Python 内部调用的 R=10000 boolean 值列表?

python - 通过索引更新列表元素

python - 无法使用 sqlalchemy 查询 json 列

python - 将 csv 文件读入 pandas 数据框中,并在某些条目中引用

python - 重命名 pandas 数据框中的多个未命名列

python - resample 在 Pandas 中给出不同的最终日期