【发布时间】:2021-08-21 15:40:23
【问题描述】:
所以我有一个函数,它返回一个包含空列表或系列的列表。我遍历一个代码列表,每个代码都会返回一个空列表或系列并将它们存储在一个列表中。
但是,在遍历所有内容后,我希望能够删除空列表,并且列表中只有系列。
def get_revenue_growth(ticker) -> pd.DataFrame:
income_statement_annually = fa.financial_statement_growth(ticker, FA_API_KEY, period="annual")
if 'revenueGrowth' in income_statement_annually.index:
revenue_growth = income_statement_annually.loc['revenueGrowth']
exchange_df = pd.DataFrame({ticker : revenue_growth})
exchange_df.index = pd.to_datetime(pd.Series(exchange_df.index))
exchange_df = exchange_df[exchange_df.index.year >= 1998]
exchange_df = exchange_df.sort_index()
print('Getting Revenue Growth for ' + ticker + ': Passed')
else:
print('Getting Revenue Growth for ' + ticker + ': Failed')
exchange_df = []
return exchange_df
这是我通过这个调用的函数:
revenue_growth = [get_revenue_growth(t) for t in tickers]
Here is what the output looks like...
所以我想要实现的是删除所有空列表。我试过这个list2 = [x for x in list1 if x != []],但没用。
【问题讨论】:
-
试试:
list2 = [x for x in list1 if x] -
或者这个list2 = [x for x in list1 if len(x)>0]
-
@JonSG 我之前试过这个,很遗憾得到错误
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). -
@Cristian 行得通!非常感谢
-
让我添加答案
标签: python pandas list dataframe series