Python Help

Hachiko15

Well-known member
  • Jul 17, 2018
    795
    398
    63
    Yaluwane help ekak dennako meka karagnna
    mata poddak meka karana vidiya kiya dunnaam ethi
    Python walin



    A file named


    weather_2023-02.csv

    contains hourly weather observations


    AbbreviationMeaning
    TATemperature Average
    RHRelative Humidity
    WSWind Speed
    WDWind Direction
    PRAPrecipitation Amount
    PRIPrecipitation Intensity
    PAPressure Average
    WAWAMost Significant Weather Code

    Some of the data has been encrypted with your GPG public key. Ignoring any NaN values, find out what percentage of the hourly temperature observations satisfy the following:


    The difference between the maximum and minimum temperature is within 0.6 standard deviations away from the total average of the differences between the maximum and minimum temperatures.
    mama try kara hari giye na


    Code:
    import pandas as pd
    from cryptography.fernet import Fernet, InvalidToken
    
    # Function to generate or load Fernet key
    def load_or_generate_key():
        try:
            # Load the key if exists
            with open("fernet_key.key", "rb") as key_file:
                key = key_file.read()
        except FileNotFoundError:
            # Generate a new key if not exists
            key = Fernet.generate_key()
            with open("fernet_key.key", "wb") as key_file:
                key_file.write(key)
        return key
    
    # Decrypt the column headers and relevant data
    def decrypt_weather_data(file_path, key):
        f = Fernet(key)
        try:
            with open(file_path, "rb") as encrypted_file:
                encrypted_data = encrypted_file.read()
                decrypted_data = f.decrypt(encrypted_data)
                # Decode the decrypted data as UTF-8 and split it into lines
                decrypted_lines = decrypted_data.decode("utf-8").split("\n")
                # Extract column headers
                column_headers = decrypted_lines[0].split(",")
                # Extract relevant data
                data = []
                for line in decrypted_lines[1:]:
                    if line.strip():  # Skip empty lines
                        row = line.split(",")
                        if len(row) == len(column_headers):  # Ensure the row has the correct number of columns
                            data.append(row)
                return column_headers, data
        except InvalidToken:
            print("Error: Invalid decryption key or corrupt file.")
            return None, None
    
    # Main function
    def main():
        # Load or generate Fernet key
        key = load_or_generate_key()
    
        # Decrypt the weather data
        file_to_decrypt = 'D:Assignment\\weather_2023-02.csv.encrypted'
        column_headers, data = decrypt_weather_data(file_to_decrypt, key)
    
        if column_headers and data:
            # Create DataFrame from decrypted data
            df = pd.DataFrame(data, columns=column_headers)
    
            # Check if expected columns exist
            expected_cols = ['TA_PT1H_MAX', 'TA_PT1H_MIN']
            if not all(col in df.columns for col in expected_cols):
                missing_cols = [col for col in expected_cols if col not in df.columns]
                print(f"Error: Expected columns {', '.join(missing_cols)} not found in data.")
                return
    
            # Extract relevant columns
            df_filtered = df[expected_cols]
    
            # Calculate temperature differences
            df_filtered['temp_diff'] = df_filtered['TA_PT1H_MAX'] - df_filtered['TA_PT1H_MIN']
    
            # Handle NaN values
            df_filtered = df_filtered.dropna()
    
            # Calculate mean and standard deviation
            mean_diff = df_filtered['temp_diff'].mean()
            std_diff = df_filtered['temp_diff'].std()
    
            # Identify observations within the specified range
            filtered_df = df_filtered[(df_filtered['temp_diff'] >= mean_diff - 0.6 * std_diff) & (df_filtered['temp_diff'] <= mean_diff + 0.6 * std_diff)]
    
            # Calculate the percentage
            percentage = (filtered_df.shape[0] / df_filtered.shape[0]) * 100
    
            print("Column Headers:")
            print(column_headers)
            print("\nFirst Few Rows of Decrypted Data:")
            print(df.head())  # Display the first few rows of the DataFrame
            print("\nPercentage of observations satisfying the condition:", percentage)
        else:
            print("Decryption failed or no data found.")
    
    if __name__ == "__main__":
        main()

    OutPut
    Error: Expected columns TA_PT1H_MAX, TA_PT1H_MIN not found in data.
     

    EKGuest

    Well-known member
  • Nov 16, 2022
    3,206
    5,703
    113
    Bump machan. I don't know python and have no idea about encryption and standard deviation calculations.
    ඩේටා ෆයිල් එකයි encryption key එකයි දැම්මොත් පයිතන් දන්න කෙනෙක් උදව් කරයි.
     
    • Like
    Reactions: Hachiko15

    Hachiko15

    Well-known member
  • Jul 17, 2018
    795
    398
    63
    Bump machan. I don't know python and have no idea about encryption and standard deviation calculations.
    ඩේටා ෆයිල් එකයි encryption key එකයි දැම්මොත් පයිතන් දන්න කෙනෙක් උදව් කරයි.
    Thank you and eka daanam machan
     

    Panda_jr

    Active member
  • Apr 25, 2023
    123
    153
    43
    Error eka awilla thiyenne CSV eke TA_PT1H_MAX, TA_PT1H_MIN columns na kiyalane.. eka poddak balanna.. CSV eke thiyana column names use karamna
     
    • Like
    Reactions: Amith0424

    Hachiko15

    Well-known member
  • Jul 17, 2018
    795
    398
    63
    sample data file eka danna.
    me tika amchan

    Error eka awilla thiyenne CSV eke TA_PT1H_MAX, TA_PT1H_MIN columns na kiyalane.. eka poddak balanna.. CSV eke thiyana column names use karamna
    column name eka hoyagnna therenne na machna. meka encrypt wela nisa
    ------ Post added on Feb 25, 2024 at 12:38 PM
     

    Attachments

    • PGP PUBLIC KEY.txt
      699 bytes · Views: 67
    • weather_2023-02.zip
      147.7 KB · Views: 173

    Hachiko15

    Well-known member
  • Jul 17, 2018
    795
    398
    63
    meke thiyenne decrypted file ekak ne, encrypted eka nadda
    API eka python walin encrypt krnna oni bro eka thama therenne natte

    Mehema thiyene

    Some of the data has been encrypted with your GPG public key. Ignoring any NaN values, find out what percentage of the hourly temperature observations satisfy the following
     

    EKGuest

    Well-known member
  • Nov 16, 2022
    3,206
    5,703
    113
    Ow brother

    පේන විදියට ඔය ෆයිල් එකේ තුන්වෙනි කොලම් එකේ සමහර වැලිවුස් විතරයි එන්ක්‍රිප්ට් කරලා තියෙන්නේ.
    තව private key ෆයිල් එකක් තිබුනේ නැද්ද?
     

    Hachiko15

    Well-known member
  • Jul 17, 2018
    795
    398
    63
    පේන විදියට ඔය ෆයිල් එකේ තුන්වෙනි කොලම් එකේ සමහර වැලිවුස් විතරයි එන්ක්‍රිප්ට් කරලා තියෙන්නේ.
    තව private key ෆයිල් එකක් තිබුනේ නැද්ද?
    Na mcn ,
     

    hasithayad

    Well-known member
  • Sep 28, 2011
    30,793
    1
    44,991
    113
    Some of the data has been encrypted with your GPG public key. Ignoring any NaN values, find out what percentage of the hourly temperature observations satisfy the following
    account settings වල බලන්න කොහේහරි public key, private key තියනවද කියල