You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

带条件的If语句操作及从DataFrame的column$date提取年份(102009→2009)

Solutions to Your Two Tasks

1. Conditional If Statement to Extract 4 Characters

Let's start with the first task—assuming you're working with a value (numeric or string) where you need to validate a condition before pulling 4 characters. Since your second task involves grabbing a year from 102009, I'll use extracting the last 4 digits as an example (adjust the slicing if you need characters from a different position):

input_val = 102009  # Could also be a string like "102009"

# Convert to string to handle both numeric and string inputs
input_str = str(input_val)

# Conditional check: ensure the input has at least 4 characters
if len(input_str) >= 4:
    extracted_chars = input_str[-4:]
    print(f"Extracted 4 characters: {extracted_chars}")
else:
    print("Input is too short to extract 4 characters!")

This snippet first standardizes the input to a string, checks if it meets the length requirement, then slices the last 4 characters. Swap [-4:] with [:4] if you need the first 4 characters instead.

2. Extract Year from DataFrame's column$date Column

Moving on to your pandas DataFrame problem—since column$date has values like 102009 (6-digit numbers/strings), we can use pandas' built-in string tools to pull the year (last 4 digits) efficiently:

import pandas as pd

# Sample DataFrame matching your scenario
df = pd.DataFrame({"column$date": [102009, 052015, 122022]})

# Convert column to string, extract last 4 digits, and cast back to integer (optional)
df["extracted_year"] = df["column$date"].astype(str).str[-4:].astype(int)

print(df)

Sample Output:

column$date  extracted_year
0        102009            2009
1         52015            2015
2        122022            2022

If your column$date values are already stored as strings, you can skip the astype(str) step. This method processes the entire column in one go, which is perfect for pandas workflows.


内容的提问来源于stack exchange,提问作者BEN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:11:05