admin管理员组

文章数量:1129251

I have an excel sheet contain the following data:

Date counts
1446/05/25 12
1446/05/26 2
1446/05/26 6
1446/05/26 1
1446/05/26 1
1446/05/26 6
1446/05/27 6
1446/05/27 6
1446/05/28 4
1446/05/28 6
1446/05/29 9

I have an excel sheet contain the following data:

Date counts
1446/05/25 12
1446/05/26 2
1446/05/26 6
1446/05/26 1
1446/05/26 1
1446/05/26 6
1446/05/27 6
1446/05/27 6
1446/05/28 4
1446/05/28 6
1446/05/29 9

where I want to plot them together. But my problem is I have a duplicated date in x shown in plot. How to make them unique by summing up the counts and show unique date?

Share Improve this question edited Jan 8 at 16:29 Yousra Gad asked Jan 8 at 15:18 Yousra GadYousra Gad 3633 silver badges15 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

You need to make visualization using Gregorian dates - which is standard for plotting libraries.

Use this - https://pypi.org/project/hijri-converter/2.1.1/

import pandas as pd
import matplotlib.pyplot as plt
from hijri_converter import Hijri, Gregorian


data = {
    'Date': [
        '1446/05/25', '1446/05/26', '1446/05/26', '1446/05/26', 
        '1446/05/26', '1446/05/26', '1446/05/27', '1446/05/27',
        '1446/05/28', '1446/05/28', '1446/05/29'
    ],
    'Counts': [12, 2, 6, 1, 1, 6, 6, 6, 4, 6, 9]
}


df = pd.DataFrame(data)


def hijri_to_gregorian(date_str):
    year, month, day = map(int, date_str.split('/'))
    hijri_date = Hijri(year, month, day)
    greg_date = hijri_date.to_gregorian()
    return pd.Timestamp(greg_date.year, greg_date.month, greg_date.day)


df['Gregorian_Date'] = df['Date'].apply(hijri_to_gregorian)
df['Hijri_Date'] = df['Date']


grouped_df = df.groupby('Gregorian_Date')['Counts'].sum().reset_index()


plt.figure(figsize=(12, 6))
plt.plot(grouped_df['Gregorian_Date'], grouped_df['Counts'], marker='o')
plt.gcf().autofmt_xdate()  
plt.title('Counts by Date (Gregorian Calendar)')
plt.xlabel('Date')
plt.ylabel('Total Counts')
plt.grid(True)
plt.tight_layout()
plt.show()

Code reference - Convert Hijri (Islamic Date) to Gregorian

The aggrigated data will look like this

Gregorian Date | Total Counts
------------------------------
2024-11-27 (1446/05/25) | 12
2024-11-28 (1446/05/26) | 16
2024-11-29 (1446/05/27) | 12
2024-11-30 (1446/05/28) | 10
2024-12-01 (1446/05/29) | 9

本文标签: pythonExtract Hijri date from excel file and plot itStack Overflow