当列名称包含“ XXX”时计算非空单元格的数量

时间:2019-10-29 18:58:51

标签: python pandas dataframe

我有59列,其名称的格式为:nn: xxxxxx (ttttttt),其中tttttt是为某些特定列重复的名称。现在,我想计算tttttt='XXXXXX'时非空单元格的总和。我知道如何计算列中非空单元格的数量,但是如何在列名中添加tttttXXXXXX的条件?

import pandas as pd
df = pd.read_csv("dane.csv", sep=';')
shape = list(df.shape)
nonempty=df.apply(lambda x: shape[0]-x.isnull().sum())

输入:

1: Brandenburg (Post-Panamax)               2: Acheron (Feeder)                        5: Fenton (Feeder)
ES-NL-10633096/1938/X1@hkzydbezon.dk/6749   DE-JP-20438082/2066/A2@qwinfhcaer.cu/68849 NL-LK-02275406/2136/A1@ozmmfdpfts.de/73198
BE-BR-61613986/3551/B1@oqk.bf/39927         NL-LK-02275406/2136/A1@ozmmfdpfts.de/73198
PH-SA-39552610/2436/A1@venagi.hr/80578
PA-AE-59814691/4881/X1@zhicvzvksl.cl/25247  OM-PH-31303222/3671/Z1@jtqy.ml/52408

例如,对于此输入,假设我要计算“ Feeder”列中名称的非空单元格数量

1 个答案:

答案 0 :(得分:2)

您可以使用filter

df.filter(like='(Feeder)').isna().sum()

或更精确的版本,要求(Feeder)出现在列的末尾:

df.filter(regex='.*(\(Feeder\))$').isna().sum()

输出:

2: Acheron (Feeder)    1
5: Fenton (Feeder)     3
dtype: int64