如何根据特定条件加入不同的数据框?

问题描述 投票:0回答:1

在我的 MySQL 数据库 stocks 中,我有 3 个不同的表。 我想加入所有这些表格以显示我想要看到的精确格式。我应该先加入mysql,还是应该先将每个表提取为数据框,然后再加入pandas?应该怎么做?我也不知道代码。

这就是我想要显示的方式:https://www.dropbox.com/s/fc3mll0q3vefm3q/expected%20output%20sample.csv?dl=0

因为这只是一个示例格式,它只显示两个代码。预期的应该包括我数据中的所有代码。

所以每个代码都是一行,包含我表中的所有特定列。

补充资料:

  • 我只需要显示最近的8个季度季度和5年的年度来显示

  • 不同代码的季度数据的确切日期可能不同。如果手工完成,可以很容易地将最近的八个季度复制并粘贴到相应的列中,但是我不知道如何用计算机来确定它属于哪个季度并将其显示在与我相同的列中示例输出。 (我使用术语 q1 到 q8 只是作为要显示的列名称。因此,如果我最近的数据是 5 月 30 日,则 q8 不一定是第二年的最后一个季度。

  • 如果一个代码的最近季度或年份不可用(如示例中的“ADUS”),但其他代码可用,例如示例中的“BA”,只需将该代码留空即可。

第一张表company_infohttps://www.dropbox.com/s/g95tkczviu84pnz/company_info.csv?dl=0包含公司信息数据:

第二张表income_statement_qhttps://www.dropbox.com/s/znf3ljlz4y24x7u/income_statement_q.csv?dl=0包含季度数据:

第三表 income_statement_yhttps://www.dropbox.com/s/zpq79p8lbayqrzn/income_statement_y.csv?dl=0 包含年度数据:

python pandas dataframe join mysql-python
1个回答
1
投票

您可以使用:

# Convert as datetime64 if necessary
df2['date'] = pd.to_datetime(df2['date'])  # quarterly
df3['date'] = pd.to_datetime(df3['date'])  # yearly

# Get end dates
qmax = df2['date'].max()
ymax = df3['date'].max()

# Create date range (8 periods for Q, 5 periods for Y)
qdti = pd.date_range( qmax - pd.offsets.QuarterEnd(8), qmax, freq='Q')
ydti = pd.date_range( ymax - pd.offsets.YearEnd(5), ymax, freq='Y')

# Filter and reshape dataframes
qdf = (df2[df2['date'].isin(qdti)]
                      .assign(date=lambda x: x['date'].dt.to_period('Q').astype(str))
                      .pivot(index='ticker', columns='date', values='netIncome'))

ydf = (df3[df3['date'].isin(ydti)]
                      .assign(date=lambda x: x['date'].dt.to_period('Y').astype(str))
                      .pivot(index='ticker', columns='date', values='netIncome'))

# Create the expected dataframe
out = pd.concat([df1.set_index('ticker'), qdf, ydf], axis=1,
                keys=['Company', 'QNetIncome', 'YNetIncome'])

输出:

>>> out
                                         Company                                                             ...  YNetIncome                                                                     
                                        industry                  sector     pe    roe     shares marketCap  ...        2017          2018         2019          2020          2021          2022
ticker                                                                                                       ...                                                                                 
ADUS            Health Care Providers & Services             Health Care  38.06   7.56   16110400    1717.0  ...  13461000.0  1.737700e+07   25811000.0  3.313300e+07  4.512600e+07           NaN
BA                           Aerospace & Defense             Industrials    NaN   0.00  598240000  127359.0  ...         NaN  1.046000e+10 -636000000.0 -1.194100e+10 -4.290000e+09 -5.053000e+09
CAH             Health Care Providers & Services             Health Care    NaN   0.00  257639000   20567.0  ...         NaN           NaN          NaN           NaN           NaN           NaN
CVRX            Health Care Equipment & Supplies             Health Care   0.26 -32.50   20633700     353.0  ...         NaN           NaN          NaN           NaN -4.307800e+07 -4.142800e+07
IMCR                               Biotechnology             Health Care    NaN -22.30   47905000    2957.0  ...         NaN -7.163000e+07 -103931000.0 -7.409300e+07 -1.315230e+08           NaN
NVEC    Semiconductors & Semiconductor Equipment  Information Technology  20.09  28.10    4830800     367.0  ...         NaN           NaN          NaN           NaN           NaN           NaN
PEPG                               Biotechnology             Health Care    NaN -36.80   23631900     404.0  ...         NaN           NaN          NaN -1.889000e+06 -2.728100e+07           NaN
VRDN                               Biotechnology             Health Care    NaN -36.80   40248200    1337.0  ... -30312000.0 -2.210300e+07  -28773000.0 -1.279150e+08 -5.501300e+07           NaN

[8 rows x 21 columns]
© www.soinside.com 2019 - 2024. All rights reserved.