Read Python Excel File

Asked 1 years ago, Updated 1 years ago, 306 views

In the Excel file, if the first row is the year, the first column is the city name, and it's filled with the year, the population by city, in Python. A is the year and b is the name of the Excel file. I need to print out the number of people by country in year a, how do I do it?

def citizens(a, b):

import csv
file = open(b, 'r')
rdr = csv.reader(file)
for line in rdr

I can't move on after this. Help me.

python

2023-03-08 23:15

1 Answers

I didn't replay it either. If you ask ChatGPT, it answers like this.

The Pantas library makes it easy to read and process data from Excel files.

Below is a code that reads an Excel file using pandas and prints the number of people corresponding to a specific year and city name.

import pandas as pd

# Read Excel File
df = pd.read_excel(b + '.xlsx', index_col=0)

# Output of population by country in year a
a = 2022 # Year to print
city = 'Seoul' # Name of city to print
population = df.loc[city, str(a)] # Number of people in the city, year
print(number of {a} years of population in f"{city}: {population}")

In the code above, the function read_excel() reads the excel file. index_col=0 is the first column enabled as the index.

And use the loc function to find the number of people in that city and year. The first factor in the loc function is the index (where is the city name), and the second factor is the column (where is the year). So df.loc [city, str(a)] gets the city city and the population in year a.

The output will be shown below.


2023-03-09 00:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.