Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

python - How to get a zero column when filtering for something with no results?

I'm trying to filter for something, but if there are no results I want to get a 'zero' column rather than a blank df. I need this because it gets fed into a summation equation further down and having it blank screws it all up. See:

>>> df
    id    name    price     qty
    0001   'bob'    100     4
    0001   'bob'     67     5
    0001   'bob'     63     6
    0002  'jack'     67     3
    0002  'jack'     98     7
    0002  'jack'     90     12
    0003  'jack'     60     3
    0003  'jack'     78     7 
    0003  'rose'     87     15

df_jim_frank_qty = df[df['name'].isin(['jim','frank'])]
df_jim_frank_qty

>>> df_jim_frank_qty
    id    name    price     qty

I need it to look like this:

>>> df_jim_frank_qty
    id    name    price     qty
    NaN   NaN     NaN       0

I suspect I have to put some kind of IF argument in there and manually create that, but I'm not sure how. Any thoughts?

Thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Check condition with df.empty. If True, then use pd.concat with pd.Series:

In [1063]: y = df[df['name'].isin(['jim','frank'])]

In [1068]: if y.empty:
      ...:     x = pd.concat([y, pd.Series([np.nan, np.nan, np.nan, 0])], 1).dropna(how='all')
      ...: 

In [1069]: x
Out[1069]: 
   id name  price  qty    0
3 NaN  NaN    NaN  NaN  0.0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...