Home > other >  python define values for each data-frame if they meet a condition
python define values for each data-frame if they meet a condition

Time:06-04

i have 5 different data frames that are output of different conditions or tables.

i want to have an output if these data-frames are empty or not. basically i will define with len(df) each data frame and will pass a string if they have anything in them.

def(df1,df2,df3,df4,df5)

if len(df1) > 0:
"df1 not empty"
else: ""

if len(df2) > 0:
"df2 not empty"
else: ""

then i want to append these string to each other and will have a string like

**df1 not empty, df3 not empty**

CodePudding user response:

try this :

import pandas as pd

dfs = {'milk': pd.DataFrame(['a']), 'bread': pd.DataFrame(['b']), 'potato': pd.DataFrame()}

print(''.join(
    [f'{name} not empty. ' for name, df in dfs.items() if (not df.empty)])
      )

output:

milk not empty. bread not empty. 

CodePudding user response:

data = [1,2,3]
df = pd.DataFrame(data, columns=['col1']) #create not empty df

data1 = []
df1 = pd.DataFrame(data) #create empty df

dfs = [df, df1] #list them

#the "for loop" is replaced here by a list comprehension
#I used enumerate() to attribute an index to each df in the list of dfs, because otherwise in the print output if you call directly df0 or df1 it will print th entire dataframe, not only his name
print(' '.join([f'df{i} is not empty.' for i,df in enumerate(dfs) if not df.empty]))

Result:

df0 is not empty. df1 is not empty.

CodePudding user response:

With a one-liner:

dfs = [df1,df2,df3,df4,df5]
output = ["your string here" for df in dfs if not df.empty]

You can then concatenate strings together, if you want:

final_string = "; ".join(output)
  • Related