To remove whitespace before and after a string in Python, for example, from a product column, you can use the strip() method. Here's an example:

product = '   iPhone X    '
clean_product = product.strip()

print(clean_product)  # Output: 'iPhone X'

The strip() method removes any leading or trailing whitespace from the string. You can apply this method to a column in a Pandas DataFrame using the apply() method, like this:

import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({'Product': ['  iPhone X  ', 'Samsung Galaxy S9', '   Google Pixel 3a   ']})

# Apply the strip() method to the 'Product' column
df['Product'] = df['Product'].apply(lambda x: x.strip())

# Print the cleaned DataFrame
print(df)

This will output:

          Product
0        iPhone X
1  Samsung Galaxy S9
2    Google Pixel 3a

In this example, we use a lambda function to apply the strip() method to each element in the 'Product' column.

Python: Remove Leading and Trailing Whitespace from Strings (Product Column)

原文地址: https://www.cveoy.top/t/topic/nTLl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录