我有一个带有一堆名称和系列的 python pandas 数据框,我创建了一个总结系列的最后一列。我只想获取系列总和等于 0 的行名称,以便稍后删除这些行。我的数据框如下(我创建的最后一列只是为了总结该系列):
1 2 3 4 total
Ash 1 0 1 1 3
Bel 0 0 0 0 0
Cay 1 0 0 0 1
Jeg 0 1 1 1 3
Jut 1 1 1 1 4
根据最后一列,系列“Bel”为 0,因此我希望能够仅打印出该名称,然后我可以删除该行或保留这些行的记录。
到目前为止,这是我的代码:
def check_empty(df):
df['total'] = df.sum(axis=1) # create the 'total' column to find zeroes
for values in df['total']:
if values == 0:
print(df.index[values)
但这显然是错误的,因为我将索引 0 传递给这个循环,它总是打印第一行的名称。不确定我可以在这里实现什么方法?
下面有很好的解决方案,我还找到了一种使用更简单的 python 技能的方法,枚举(因为我仍然觉得列表理解很难写):
def check_empty(df):
df['total'] = df.sum(axis=1)
for name, values in enumerate(df['total']):
if values == 0:
print(df.index[name])
请您参考如下方法:
一种可能的方法是使用 total 中的值过滤 df:
def check_empty(df):
df['total'] = df.sum(axis=1) # create the 'total' column to find zeroes
index = df[df['total'] == 0].index.values.tolist()
print(index)
如果您想遍历行,那么使用 df.iterrows() 也可能是其他方式:
def check_empty(df):
df['total'] = df.sum(axis=1) # create the 'total' column to find zeroes
for index, row in df.iterrows():
if row['total'] == 0:
print(index)
