简体   繁体   English

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

[英]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.我有 5 个不同的数据框,它们是 output 的不同条件或表格。

i want to have an output if these data-frames are empty or not.如果这些数据帧是否为空,我想要一个 output。 basically i will define with len(df) each data frame and will pass a string if they have anything in them.基本上我会用 len(df) 定义每个数据帧,如果它们有任何内容,将传递一个字符串。

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然后我想将 append 这些字符串相互连接,并且会有一个类似的字符串

**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: 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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