我需要更改df2
列类型详细信息中提到的df1
列数据类型。
示例:age
需要更改为int
,salary
需要更改为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
这里是一种方式:
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
[这是使用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)