使用 astype 更改列类型不起作用 - 目标进行连接

Changing Column type using astype does not work - Goal make a Join

我需要连接到表中,为此,我需要更改列类型但没有更改。这是我的代码,数据集是开源的。

import pandas as pd
import json
from urllib.request import urlopen

#Get Data
url = 'https://raw.githubusercontent.com/sthemonica/alura-voz/main/Dados/Telco-Customer-Churn.json'
response = urlopen(url)
strfile = response.read().decode('utf-8', 'replace')
jsonfile = json.loads(strfile)
dft = pd.json_normalize(data=jsonfile)

# My Problem
print('Before', dft['Churn'].dtypes)
dft = dft.astype({'Churn': str})
print('After', dft['Churn'].dtypes)

结果:

Before object
After object

注意,我也试试:

dft = dft.astype({'Churn': "str"})
dft.astype({'Churn': "str"})
dft.astype({'Churn': str})

我做错了什么?这是加入要做什么:

dtemp = [[0, 'No'],
     [1, 'Yes']]
columns_names = ['Id', 'Churn']
df_FromTo = pd.DataFrame(data=dtemp, columns=columns_names)
dft = dft.join(df_FromTo, on='Churn', rsuffix="_del")

结果:

ValueError: You are trying to merge on object and int64 columns. If you wish to proceed you should use pd.concat
 dft = dft.merge(df_FromTo, on='Churn')

参见pandas.DataFrame.join on参数解释

Column or index level name(s) in the caller to join on the index in other, otherwise joins index-on-index.

当您执行 dft.join(df_FromTo, on='Churn', rsuffix="_del") 时,callerdftotherdf_FromTo,您正在加入 dft['Churn']df_FromTo.index

您可以使用

修复
dft = dft.join(df_FromTo.set_index('Churn'), on='Churn', rsuffix="_del")