特定のデータフレーム列をint型に変換したい(注:私のデータフレームは現在の例よりも多く、非常に動的である可能性があるため、変換するための最良の方法を見つけたいと思います)。
コード:
import pandas as pd
import numpy as np
df_p = pd.DataFrame({'1.0': [1,2,3],
'2.0': [4,5,6],
'3.0': [7,8,9],
'4.0': [4,5,6],
'5.0': [4,5,6],
'6.0': [1,1,1],
'info': ['abc','dfg','ghj'],
'new_info': [4,5,6],
'new_t_info': ['your','master','data']})
df_p.columns.astype(int) #Normally I use this to convert it, however, since my columns contain string that cannot be converted to int then I am lost. Please note, I might have more than the current columns and wish to find a more dynamic ways to do it.
電流 :
1.0 2.0 3.0 4.0 5.0 6.0 info new_info new_t_info
0 1 4 7 4 4 1 abc 4 your
1 2 5 8 5 5 1 dfg 5 master
2 3 6 9 6 6 1 ghj 6 data
期待:
1 2 3 4 5 6 info new_info new_t_info
0 1 4 7 4 4 1 abc 4 your
1 2 5 8 5 5 1 dfg 5 master
2 3 6 9 6 6 1 ghj 6 data
使用DataFrame.sort_index
後、我々が使用することができ、以前のコードを適用する前pd.to_numeric
にerrors = 'coerce'
してのpd.Index.to_series
+ Series.replace
:
df_p=df_p.sort_index(axis=1)
s = df_p.columns.to_series()
df_p.columns = s.replace(pd.to_numeric(s,errors = 'coerce').dropna().astype(int))
# 1 2 3 4 5 6 info new_info new_t_info
#0 1 4 7 4 4 1 abc 4 your
#1 2 5 8 5 5 1 dfg 5 master
#2 3 6 9 6 6 1 ghj 6 data
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加