简体   繁体   中英

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

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**
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.

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. 

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM