Python filter gives empty dataframe along with the filtered rows

Viewed 57

I am doing basic filter on a python dataframe.Below is the code.

df1 = df.loc[df['ID'] == '2f45b-ii58-4927']
print(df1)

It gives me empty dataframe along with the filtered rows like below.

Empty DataFrame
Columns: []

     Date  sal       ID
0  14Jun   10100  2f45b-ii58-4927

I don t need the empty dataframe part along with the filtered rows .Is there any way to achieve this. The reason I do not need the empty dataframe part is I am calling this python function in a Azure function. The Python function will read the json files recursively from azure storage into a dataframe, filter the dataframe and gives the output. If the filtered row is not from the first file the function read, the Azure function gives output as []

Thank you.

Edit: Below is the code.

from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
import json
import json
import pandas as pd
from pandas import DataFrame
from datetime import datetime
import uuid

filename = "raw/filename.json"

container_name="test"
constr = ""

blob_service_client = BlobServiceClient.from_connection_string(constr)
container_client = blob_service_client.get_container_client(container_name)
blob_client = container_client.get_blob_client(filename)
streamdownloader = blob_client.download_blob()

fileReader = json.loads(streamdownloader.readall())
df = pd.DataFrame(fileReader)
df1= df[df['ID'] == '2f45b-ii58-4927']
df1.head()

Below is the output.

Empty DataFrame
Columns: [Date,sal,ID]
Index: []

     Date  sal       ID
0  14Jun   10100  2f45b-ii58-4927
2 Answers

Instead of using loc, you should do a direct filtering of the DataFrame:

df1 = df[df['ID'] == '2f45b-ii58-4927']
print(df1)

Since loc tries to find the location of the items in a Boolean (True/False) object inside the square braces, it is not able to locate the exact item as a DataFrame.

I have used below and it worked for me.

if not dfl.empty:
print(df1)
Related