这个问题似乎非常基础,并且在该问题中明确回答了该主题: Change data type of columns in Pandas
我有一个DataFrame df
。
一列名为adress
,其中包含字符串:
type(df.loc[0, 'adress'])
>>> str
#Let's check the whole column's type
df.loc[:, 'adress'].dtype
>>> dtype('O')
dtype是一个对象,我想将其更改为字符串。 我尝试过:
df.loc[:, 'adress'] = df.loc[:, 'adress'].astype(str)
df.loc[:, 'adress'].dtype
>>> dtype('O')
#and
df.loc[:, 'adress'] = df.loc[:, 'adress'].astype('str')
df.loc[:, 'adress'].dtype
>>> dtype('O')
#and
df = df.infer_objects()
df.loc[:, 'adress'].dtype
>>> dtype('O')
我不知道自己在想什么。
我还检查了整个列是否仅包含字符串:
for i in df.index:
if type(df.loc[i, 'adress']) != str:
print(i)
wait = input('Up')
print('Done')
>>>Done