如何通过引用其他在python中具有列类型详细信息的表来更改列数据类型?

问题描述 投票:2回答:2

我需要更改df2列类型详细信息中提到的df1列数据类型。

示例:age需要更改为intsalary需要更改为float

df1:

  ColumnName ColumnType  
0 Name       string   
1 Age        int   
2 emp_Id     string
3 salary     float

df2-

    Name   Age  salary  Emp_Id
0   Tom     20  1000    111
1   nick    21  2000    222
2   krish   19  4500    333
3   Tommy   18  6500    444
4   Andy    27  5666    555
5   rick    20  2866    666

df.dtypes

Name      object
Age       object
salary    object
Emp_Id    object
python python-3.x pandas function
2个回答
0
投票

这里是一种方式:

for i,r in df1.iterrows():
  if r['ColumnType'] == 'string':
    r['ColumnType'] = 'str'
  df2[r['ColumnName']] = df2[r['ColumnName']].astype(r['ColumnType'])

df2.dtypes

输出:

Name       object
Age         int64
salary    float64
Emp_Id     object
dtype: object

0
投票

[这是使用df.astype()的另一种方法,我正在将列名转换为小写以消除大小写示例df.astype()emp_Id的歧义:

Emp_Id

d=df1.set_index(df1.ColumnName.str.lower()).replace('string','str')['ColumnType'].to_dict()
#output-> {'name': 'str', 'age': 'int', 'emp_id': 'str', 'salary': 'float'}
final=df2.rename(columns=lambda x: x.lower()).astype(d)
print(final.dtypes)
© www.soinside.com 2019 - 2024. All rights reserved.