如何合并来自 2 个不同 panda 数据帧的变量进行绘图?

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

我有第一个 CSV panda 数据框,如下所示:

            Date_reported  Country   New_cases  Cumulative_cases  
     0       23-Feb-20    Singapore      10             10
     0       26-Mar-20    Singapore      100            110
     0       27-Apr-20    Singapore      200            310
     0       28-May-20    Singapore      400            710
     0       30-Jun-20    Singapore      1000           1710

我设法以这种形式制作出每月案例的分组数据:

    Date_reported
    February      10
    March        100
    April        200
    May          400
    June        1000
 

使用此代码:

  df = pd.read_csv('Stackoverflow1.csv')
  df['Date_reported'] = pd.to_datetime(df['Date_reported'])
  df.groupby(df['Date_reported'].dt.strftime('%B'))['New_cases'].sum().sort_values()  
   

我还有第二个这样的熊猫数据框:

  Variables       2020 Feb  2020 Mar  2020 Apr  2020 May  2020 June   
 Hotel Revenue       $100      $90      $80       $70       $60
 Occupancy Rate       80%       70%     60%       50%        40%

我的最终结果是根据各个月份合并第一个数据帧中每月报告病例的数据和第二个数据帧中的变量(即针对酒店收入的每月新冠病例)并绘制一个简单的图表。

   Date_reported    Monthly_cases   Hotel Revenue Occupancy Rate
February                  10           $100           80%
March                     100          $90            70%
April                     200          $80            60%
May                       400          $70            50%
June                      1000         $60            40%

但是,我遇到了两个问题:

  1. 尽管我设法制作了每月摘要,但我无法将每月案例本身的分组数据转换为列表来针对第二个数据框中的变量进行绘图。

  2. 虽然我设法使用此代码转置第二个数据帧,

       hotel = pd.read_csv('Stackoverflow2.csv')
       hotel2 = hotel.T
       headers = hotel2.iloc[0]
       hotel2 = pd.DataFrame(hotel2.values[1:], columns=headers)
    

我没有日期作为索引,如下所示:

Variables       Hotel Revenue  Occupancy Rate      
 2020 Feb           $100           80%
 2020 Mar           $90            70%
 2020 Apr           $80            60%
 2020 May           $70            50%
 2020 Jun           $60            40%

非常感谢您的帮助,因为我是一个正在与 pandas 和 python 斗争的初学者。如果您有更好的方式来展示这一点,请告诉我。谢谢。

javascript python c++ pandas dataframe
1个回答
0
投票

为了解决将每月案例数据与酒店绩效数据合并并绘制结果的问题,您可以首先从第一个 DataFrame 中按月对案例进行分组。接下来,通过转置第二个 DataFrame 并提取月份名称,将其转换为将月份作为行。将两个 DataFrame 合并到共同的月份名称上。最后,使用双轴图绘制数据,以可视化每月案例与酒店收入之间的关系。

  1. 对第一个数据帧中的每月案例进行分组

您已经成功对每月案例进行分组。让我们将这些分组数据保存到一个新的 DataFrame 中:

import pandas as pd

# Read the first CSV
df = pd.read_csv('Stackoverflow1.csv')

# Convert the 'Date_reported' column to datetime
df['Date_reported'] = pd.to_datetime(df['Date_reported'])

# Group by month and sum 'New_cases'
monthly_cases = df.groupby(df['Date_reported'].dt.strftime('%B'))['New_cases'].sum().reset_index()
monthly_cases.columns = ['Date_reported', 'Monthly_cases']
  1. 转换第二个数据框

接下来,让我们读取并转换第二个 DataFrame 以将月份作为行:

# Read the second CSV
hotel = pd.read_csv('Stackoverflow2.csv')

# Transpose the dataframe
hotel2 = hotel.T

# Set the first row as the header
hotel2.columns = hotel2.iloc[0]
hotel2 = hotel2[1:]

# Reset the index to have the months as a column
hotel2 = hotel2.reset_index()
hotel2.columns.name = None

# Rename the columns
hotel2.rename(columns={'index': 'Date_reported'}, inplace=True)
  1. 合并两个数据框

我们需要确保 Date_reported 列匹配。 Monthly_cases DataFrame 只有月份名称,因此我们需要从 hotel2 的 Date_reported 列中提取月份部分

# Extract month names from the second DataFrame
hotel2['Date_reported'] = pd.to_datetime(hotel2['Date_reported'],  format='%Y %b').dt.strftime('%B')

接下来,合并两个 DataFrame:

# Merge the DataFrames on 'Date_reported'
merged_df = pd.merge(monthly_cases, hotel2, on='Date_reported')
  1. 绘图

现在您已经有了合并的 DataFrame,您可以绘制数据了。

© www.soinside.com 2019 - 2024. All rights reserved.