我在df.to_csv行上得了KeyError: "['CashFinancial'] not in index"分,因为‘GOOG’没有CashFinancial列.我怎么能让它在null中写下‘GOOG’的CashFinancial值呢?

import pandas as pd
from yahooquery import Ticker
symbols = ['AAPL','GOOG','MSFT'] #This will be 75,000 symbols.
header = ["asOfDate","CashAndCashEquivalents","CashFinancial","CurrentAssets","TangibleBookValue","CurrentLiabilities","TotalLiabilitiesNetMinorityInterest"]

for tick in symbols:
    faang = Ticker(tick)
    faang.balance_sheet(frequency='q')
    df = faang.balance_sheet(frequency='q')
    df.to_csv('output.csv', mode='a', index=True, header=False, columns=header)

推荐答案

关于以下几点:

if tick == "GOOG"
    df.loc[:,"CashFinancial"] = None

在将整个CashFinancial列写入CSV之前,仅当您的"Tick"为GOOG时才将其设置为"None".

您发布的示例中的完整代码类似于:

import pandas as pd
from yahooquery import Ticker
symbols = ['AAPL','GOOG','MSFT']
header = ["asOfDate","CashAndCashEquivalents","CashFinancial","CurrentAssets","TangibleBookValue","CurrentLiabilities","TotalLiabilitiesNetMinorityInterest"]

for tick in symbols:
    faang = Ticker(tick)
    faang.balance_sheet(frequency='q')
    df = faang.balance_sheet(frequency='q')#,{"symbol":[1],"asOfDate":[2],"CashAndCashEquivalents":[3],"CashFinancial":[4],"CurrentAssets":[5],"TangibleBookValue":[6],"CurrentLiabilities":[7],"TotalLiabilitiesNetMinorityInterest":[8],"marketCap":[9]}
    for column_name in header :
        if not column_name in df.columns :
            #Here, if any column is missing from the names you defined 
            #in your "header" variable, we add this column and set all 
            #it's row values to None
            df.loc[:,column_name  ] = None
    
    df.to_csv('output.csv', mode='a', index=True, header=False, columns=header)

Python相关问答推荐

在Python中对分层父/子列表进行排序

如果条件为真,则Groupby.mean()

max_of_three使用First_select、second_select、

如何避免Chained when/then分配中的Mypy不兼容类型警告?

如何在类和classy-fastapi -fastapi- followup中使用FastAPI创建路由

如何在Python中并行化以下搜索?

Julia CSV for Python中的等效性Pandas index_col参数

如何请求使用Python将文件下载到带有登录名的门户网站?

如何使用它?

导入...从...混乱

我的字符串搜索算法的平均时间复杂度和最坏时间复杂度是多少?

从旋转的DF查询非NaN值

Python将一个列值分割成多个列,并保持其余列相同

如何在Gekko中处理跨矢量优化

504未连接IB API TWS错误—即使API连接显示已接受''

在第一次调用时使用不同行为的re. sub的最佳方式

如何设置nan值为numpy数组多条件

我怎么才能用拉夫分拣呢?

将相应的值从第2列合并到第1列(Pandas )

如何从具有完整层次数据的Pandas框架生成图形?