python 为满足条件的每个数据框定义值

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

我有 5 个不同的数据帧,它们是不同条件或表的输出。

如果这些数据帧是否为空,我想要一个输出。基本上我会用 len(df) 定义每个数据帧,如果其中有任何内容,我将传递一个字符串。

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

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

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

然后我想将这些字符串附加到彼此并得到一个类似

的字符串
**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]))

结果:

df0 is not empty. df1 is not empty.

试试这个:

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)])
      )

输出:

milk not empty. bread not empty. 

与 one-liner:

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

然后,如果需要,您可以将字符串连接在一起:

final_string = "; ".join(output)