如何在Pandas DataFrame的Week列前补0(长度为1时)并合并年周
Got it, let's tackle this problem step by step. Here's how you can achieve exactly what you need with Pandas:
First, we need to pad the Week column with a leading 0 when its value has only one digit, then combine it with the Year column to create that YYYYWW format (like 201702).
Step 1: Pad the Week column with leading zeros
We’ll use Pandas' str.zfill(2) method—it’s perfect for this job because it automatically adds leading zeros to make the string length 2. Just note we need to convert the numeric Week column to a string first since this method works on text values.
Step 2: Merge Year and padded Week
Convert the Year column to a string too, then concatenate it with the padded Week values to get the final combined format.
Here’s the complete code example, using your provided DataFrame:
import pandas as pd # Your original dataset data = { 'new': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 'Week': [43, 44, 51, 2, 5, 12, 52, 53, 1, 2, 5, 52], 'Year': [2016, 2016, 2016, 2017, 2017, 2017, 2018, 2018, 2019, 2019, 2019, 2019], 'Date': ['2016-10-24', '2016-10-31', '2016-12-19', '2017-01-09', '2017-01-30', '2017-03-20', '2018-12-24', '2018-12-31', '2018-12-31', '2019-01-07', '2019-01-28', '2019-12-23'] } df = pd.DataFrame(data) # Option 1: Break it into two clear steps # Pad Week to 2 digits df['Week_padded'] = df['Week'].astype(str).str.zfill(2) # Combine Year and padded Week into a new column df['Year_Week'] = df['Year'].astype(str) + df['Week_padded'] # Option 2: Do it in one line if you don't need the intermediate column # df['Year_Week'] = df['Year'].astype(str) + df['Week'].astype(str).str.zfill(2) # Check the result print(df[['Year', 'Week', 'Year_Week']])
Sample Output
Running this code will produce a new Year_Week column with your desired format. Here’s a snippet of the result:
Year Week Year_Week 0 2016 43 201643 1 2016 44 201644 2 2016 51 201651 3 2017 2 201702 4 2017 5 201705 ...
This approach uses Pandas' vectorized string operations, which are way faster than looping through rows manually—perfect for handling larger datasets too.
内容的提问来源于stack exchange,提问作者Jonathan Lam

