如何更改 pandas 中多个数据框的单列数据类型?

How to change datatype for single column for multiple dataframes in pandas?

例如,我有 5 个数据帧,例如

df1 df2 DF3 df4 df4

在每一列中都有一个名称为 'phone_no' 的列。

我正在尝试使用 for 循环更改 phone_no 的数据类型,但它不起作用。下面是代码

df_all = [df1, df2, df3, df4, df5]

df_all = [i['phone_no'].astype(str) for i in df_all]

当我尝试打印 df_all 时,它的 returning 输出就像

[2        669263000000.0
 3        313988000000.0
 4        182100000000.0
 12       270449000000.0
 13       109617000000.0
 Name: phone_no, Length: 14042, dtype: object,
 1        466167000000.0
 8        433999000000.0
 9        323820000000.0
 11       823428000000.0
 15       659981000000.0
 Name: phone_no, Length: 13947, dtype: object,
 7        832447000000.0
 14       178296000000.0
 22       145628000000.0
 29       642982000000.0
 48       596803000000.0
 Name: phone_no, Length: 13924, dtype: object,
 0        555314000000.0
 5        110872000000.0
 19       890271000000.0
 34       634257000000.0
 37       125423000000.0
 Name: phone_no, Length: 14112, dtype: object,
 6        314615000000.0
 10       982864000000.0
 23       287164000000.0
 24       746213000000.0
 27       590169000000.0
 Name: phone_no, Length: 13686, dtype: object]

唯一的问题是,如果我 运行 上面的代码,它只是 returning 来自每个数据帧的 phone_no 列,而不是 returning 完整的数据框。如何解决这个问题?

之后如何执行下面的代码

df_all = [i['phone_no'].str[0:12] for i in df_all]

输出是

[2        669263000000
 3        313988000000
 4        182100000000
 12       270449000000
 13       109617000000
 Name: phone_no, Length: 14042, dtype: object,
 1        466167000000
 8        433999000000
 9        323820000000
 11       823428000000
 15       659981000000
 Name: phone_no, Length: 13947, dtype: object,
 7        832447000000
 14       178296000000
 22       145628000000
 29       642982000000
 48       596803000000
 Name: phone_no, Length: 13924, dtype: object,
 0        555314000000
 5        110872000000
 19       890271000000
 34       634257000000
 37       125423000000
 Name: phone_no, Length: 14112, dtype: object,
 6        314615000000
 10       982864000000
 23       287164000000
 24       746213000000
 27       590169000000
 Name: phone_no, Length: 13686, dtype: object]

以上代码在执行切片后只会从所有数据帧中 return phone_no 列。它会错过另一列。如何解决这个问题?

您可以将字典传递给 DataFrame.astype 以仅转换某些列名称:

df_all = [i.astype({'phone_no': str}) for i in df_all]

编辑:您可以处理列并分配回去:

df_all = [i.assign(phone_no = i['phone_no'].str[0:12]) for i in df_all]