簡體   English   中英

如何將最后幾列從pandas中的字符串類型轉換為整數

[英]How to convert the last several columns to integer from string type in pandas

我有一個名為df

我想將此數據幀的最后10列從字符串類型轉換為整數。 我怎么能用pythonic方式做到這一點?

我認為最快的方法是使用convert_objects並使用下標/切片表示法選擇最后10列,例如:

In [23]:

df = pd.DataFrame({'a':['1','2','3','4','5']})

df = pd.concat([df]*11, axis=1)
df.columns = list('abcdefghijk')
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 5 entries, 0 to 4
Data columns (total 11 columns):
a    5 non-null object
b    5 non-null object
c    5 non-null object
d    5 non-null object
e    5 non-null object
f    5 non-null object
g    5 non-null object
h    5 non-null object
i    5 non-null object
j    5 non-null object
k    5 non-null object
dtypes: object(11)
memory usage: 480.0+ bytes
In [21]:

converted = df[df.columns[-10:]].convert_objects(convert_numeric=True)
converted
Out[21]:
   b  c  d  e  f  g  h  i  j  k
0  1  1  1  1  1  1  1  1  1  1
1  2  2  2  2  2  2  2  2  2  2
2  3  3  3  3  3  3  3  3  3  3
3  4  4  4  4  4  4  4  4  4  4
4  5  5  5  5  5  5  5  5  5  5
In [22]:

converted.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 5 entries, 0 to 4
Data columns (total 10 columns):
b    5 non-null int64
c    5 non-null int64
d    5 non-null int64
e    5 non-null int64
f    5 non-null int64
g    5 non-null int64
h    5 non-null int64
i    5 non-null int64
j    5 non-null int64
k    5 non-null int64
dtypes: int64(10)
memory usage: 440.0 bytes

然后,您可以直接將結果分配回來:

In [31]:

df[df.columns[-10:]] = converted
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 5 entries, 0 to 4
Data columns (total 11 columns):
a    5 non-null object
b    5 non-null int64
c    5 non-null int64
d    5 non-null int64
e    5 non-null int64
f    5 non-null int64
g    5 non-null int64
h    5 non-null int64
i    5 non-null int64
j    5 non-null int64
k    5 non-null int64
dtypes: int64(10), object(1)
memory usage: 480.0+ bytes

或者用1個襯里做:

In [33]:

df[df.columns[-10:]] = df[df.columns[-10:]].convert_objects(convert_numeric=True)
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 5 entries, 0 to 4
Data columns (total 11 columns):
a    5 non-null object
b    5 non-null int64
c    5 non-null int64
d    5 non-null int64
e    5 non-null int64
f    5 non-null int64
g    5 non-null int64
h    5 non-null int64
i    5 non-null int64
j    5 non-null int64
k    5 non-null int64
dtypes: int64(10), object(1)
memory usage: 480.0+ bytes

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM