如何基于Python DataFrame首行年份格式化月份(Python 2.7)
Solution for Formatting Months with Corresponding Years in Pandas (Python 2.7)
Hey there! Since you're a beginner working with Python 2.7 and pandas, let's break this down into simple, actionable steps to get your desired output.
Step-by-Step Breakdown
First, let's clarify our goals:
- Pull the start and end years from the first row's
2017-18value (we'll get2017and2018) - Locate where
DECsits in the month row - Append the start year to all months up to and including
DEC, and the end year to every month after that
Full Working Code (Python 2.7 Compatible)
import pandas as pd # Your original DataFrame df = pd.DataFrame([['2017-18','','','','','','','','','','',''], ['APR', 'MAY', 'JUN', 'JULY', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC', 'JAN', 'FEB', 'MAR']]) # Step 1: Extract start and end years from the first row year_range = df.iloc[0, 0] # Grab the '2017-18' value start_year = year_range.split('-')[0] # Get '2017' # Convert '18' to '2018' by prepending '20' end_year = '20' + year_range.split('-')[1] # Step 2: Find the index position of 'DEC' in the month row month_row = df.iloc[1] dec_index = month_row[month_row == 'DEC'].index[0] # Step 3: Format each month with the correct year formatted_months = [] for idx, month in enumerate(month_row): if idx <= dec_index: # Use .format() instead of f-strings (f-strings don't work in Python 2.7) formatted_month = "{}-{}".format(month, start_year) else: formatted_month = "{}-{}".format(month, end_year) formatted_months.append(formatted_month) # Step 4: Create the new DataFrame with formatted months df1 = df.copy() df1.iloc[1] = formatted_months # Check the result print(df1)
Expected Output
When you run the code, df1 will match exactly what you requested:
0 1 2 3 4 5 6 7 8 9 10 11 0 2017-18 1 APR-2017 MAY-2017 JUN-2017 JULY-2017 AUG-2017 SEP-2017 OCT-2017 NOV-2017 DEC-2017 JAN-2018 FEB-2018 MAR-2018
Quick Tips for Beginners
- We use
ilocto access rows/columns by their numerical position (since your DataFrame doesn't have named labels) - Python 2.7 doesn't support modern f-strings, so we rely on the
.format()method for string concatenation - This code will automatically adjust to different year ranges (like
2018-19) without manual edits
内容的提问来源于stack exchange,提问作者PratikSharma
相关产品推荐
相关产品推荐

