如何将 Python 中包含冒号 (:) 和 space 的数据帧中的对象转换为整数?
How can I convert object to integer from the dataframe in Python with contains colon(:) and space?
数据包含冒号(:)和space,所以所有列的类型都是对象。如何将所有列对象转换为整数或浮点数。
我试过了,但是没用。
df = pd.concat([df[col].str.split()
.str[0]
.str.replace(':','').astype(float) for col in df], axis=1)
df['col'] = df['col'].astype(int)
print(df)
AttributeError: Can only use .str accessor with string values!
您可以使用正则表达式提取数字,然后将其转换为整数。请看下面的代码:
import re
def to_integer(x):
result = re.findall('[0-9]+', str(x))
num = ''.join(result)
return int(num)
df['col'] = df['col'].apply(to_integer)
数据包含冒号(:)和space,所以所有列的类型都是对象。如何将所有列对象转换为整数或浮点数。
我试过了,但是没用。
df = pd.concat([df[col].str.split()
.str[0]
.str.replace(':','').astype(float) for col in df], axis=1)
df['col'] = df['col'].astype(int)
print(df)
AttributeError: Can only use .str accessor with string values!
您可以使用正则表达式提取数字,然后将其转换为整数。请看下面的代码:
import re
def to_integer(x):
result = re.findall('[0-9]+', str(x))
num = ''.join(result)
return int(num)
df['col'] = df['col'].apply(to_integer)