假設你有一個包含整數列,花車,和字符串,這些都是從一個文件中的字符串讀入,你就會有這樣的事情:
s = pd.Series(['10', '20', '30.4', '40.7', 'text', 'more text', '50.0'])
在這種情況下,你可以應用的功能浮子爲整數,那麼第二函數到整數轉換(背面)轉換爲字符串:
import pandas as pd
def print_type(x):
print(type(x))
return x
def to_int(x):
try:
# x is a float or an integer, and will be returned as an integer
return int(pd.to_numeric(x))
except ValueError:
# x is a string
return x
def to_str(x):
return str(x)
s = pd.Series(['10', '20', '30.4', '40.7', 'text', 'more text', '50.0'])
s2 = s.apply(to_int).apply(to_str)
print("Series s:")
print(s)
print("\nSeries s2:")
print(s2)
print("\nData types of series s2:")
print(s2.apply(print_type))
這裏是輸出,顯示出的是,在結束時,每個號碼已被轉換爲一個整數的字符串版本:
Series s:
0 10
1 20
2 30.4
3 40.7
4 text
5 more text
6 50.0
dtype: object
Series s2:
0 10
1 20
2 30
3 40
4 text
5 more text
6 50
dtype: object
Data types of series s2:
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>
0 10
1 20
2 30
3 40
4 text
5 more text
6 50
dtype: object
不知道這是你以後的,但如果不是,希望它會給你一個如何開始的想法。這是使用熊貓0.19.2:
In [1]: import pandas as pd
In [2]: print(pd.__version__)
0.19.2
強制轉換爲格式化字符串,如你所願。 – MedAli
你可以發佈代碼嗎?你有一個數據框在一列中包含所有這些數據類型嗎? id列是什麼類型?我想重新創建您的問題,但我不知道該怎麼做 –
提供一些示例數據,提供您收到的回溯。我不明白你的意思是'把一個字符串轉換成int'是不合邏輯的。這是什麼意思?你的意思是你有一些字符串不是代表數字的字符串嗎? –