slice 和 select 如何仅使用第一个字符 - 就像您将 str() 用于字符串但用于数字特征一样?
How do slice and select only the first characters- like you would use str() for a character string, but for a numeric feature?
我正在尝试分割要素邮政编码的前 3 位数字并从中创建一个新变量。
Zip = 300123
newZip = Zip//1000
print(newZip)
zipcode = 75012
sliced_zipcode = str(zipcode)[:3]
# If you want the result in integer
three_digits_zipcode = int(str(zipcode)[:3])
# If you want to apply this in a dataframe
import pandas as pd
df['three_digits_zip'] = df['zipcode'].apply(lambda x: int(str(x)[:3]))
我正在尝试分割要素邮政编码的前 3 位数字并从中创建一个新变量。
Zip = 300123
newZip = Zip//1000
print(newZip)
zipcode = 75012
sliced_zipcode = str(zipcode)[:3]
# If you want the result in integer
three_digits_zipcode = int(str(zipcode)[:3])
# If you want to apply this in a dataframe
import pandas as pd
df['three_digits_zip'] = df['zipcode'].apply(lambda x: int(str(x)[:3]))