簡體   English   中英

python 為每個數據幀定義滿足條件的值

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

我有 5 個不同的數據框,它們是 output 的不同條件或表格。

如果這些數據幀是否為空,我想要一個 output。 基本上我會用 len(df) 定義每個數據幀,如果它們有任何內容,將傳遞一個字符串。

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

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

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

然后我想將 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]))

結果:

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

output:

milk not empty. bread not empty. 

使用單線:

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

如果需要,您可以將字符串連接在一起:

final_string = "; ".join(output)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM