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

如何将字符串中Titlecase单词转为小写?含DataFrame遍历需求

Convert Titlecase Words to Lowercase in a Pandas DataFrame

Got it, let's solve this problem properly. You need to go through your DataFrame and turn every Titlecase word (first letter uppercase, rest lowercase) into all lowercase, and your previous attempts haven't worked. Let's break this down with practical code and explanations.

Step 1: Identify Titlecase Words Correctly

First, Python's built-in str.istitle() method is perfect here—it returns True exactly when a string is Titlecase (like "Hello" or "Foo-Bar"), which matches your requirement. This is way more reliable than writing custom regex or character checks, especially since you mentioned looking into case detection already.

Step 2: Build a Custom Processing Function

Create a function that takes a string, splits it into words, converts only the Titlecase ones to lowercase, and joins everything back together. We'll also add a check for non-string values (like numbers or NaN) to avoid errors:

def convert_titlecase_to_lower(text):
    # Skip non-string values to prevent errors
    if not isinstance(text, str):
        return text
    # Split text into individual words
    words = text.split()
    # Convert only Titlecase words to lowercase, leave others as-is
    processed_words = [word.lower() if word.istitle() else word for word in words]
    # Join words back into a single string
    return ' '.join(processed_words)

Step 3: Apply the Function to Your DataFrame

You can apply this function to either the entire DataFrame or specific columns, depending on your needs:

Option 1: Process the Entire DataFrame

Use applymap() to run the function on every cell in the DataFrame:

import pandas as pd

# Example DataFrame
df = pd.DataFrame({
    "id": [1, 2, 3],
    "text": ["Hello World foo Bar", "HEllo Test 123 Apple", "hello Python"],
    "notes": ["Titlecase Example", "Mixed CASE", 456]
})

# Process all cells
df_processed = df.applymap(convert_titlecase_to_lower)

Option 2: Process Specific Columns

If you only need to target certain columns (e.g., a text column), use apply() instead:

df['text'] = df['text'].apply(convert_titlecase_to_lower)

Example Output

For the sample DataFrame above, the processed text column will look like this:

0    hello world foo bar
1    HEllo Test 123 apple
2          hello python
Name: text, dtype: object

Notice that only the Titlecase words (like "Hello", "Bar", "Apple", "Python") are converted to lowercase—mixed-case words like "HEllo" stay unchanged, as expected.

Edge Cases to Consider

  • Non-space separators: If your words are separated by commas, hyphens, or other characters, modify the split() call (e.g., split(',') for commas).
  • Hyphenated Titlecase words: istitle() correctly identifies strings like "Hello-World" as Titlecase, and the function will convert it to "hello-world".
  • NaN values: The function skips non-string types, so NaNs or numbers will remain untouched.

内容的提问来源于stack exchange,提问作者A.Papa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:16:44