2017-09-21 33 views
0

我有一個帶有混合數據類型的ID列,當我轉動時,這會導致我遇到問題。我有一些ID爲浮點類型,所以當我嘗試將它們轉換爲整數時,然後轉換爲字符串。如果我將整個列轉換爲列,則字符串子集會拋出錯誤,因爲將字符串轉換爲int值是不合邏輯的。如何使用多個數據類型在Pandas中投射列?

我也知道,在列上迭代時突變數據類型是一個壞主意。有沒有人有任何想法?

這裏有一個直觀表示:

ID

  1. 海峽
  2. 詮釋
  3. 浮動

試圖將它們全部轉換爲字符串。另外,希望浮點數的'.0'結尾不在那裏。有任何想法嗎?

+0

強制轉換爲格式化字符串,如你所願。 – MedAli

+1

你可以發佈代碼嗎?你有一個數據框在一列中包含所有這些數據類型嗎? id列是什麼類型?我想重新創建您的問題,但我不知道該怎麼做 –

+0

提供一些示例數據,提供您收到的回溯。我不明白你的意思是'把一個字符串轉換成int'是不合邏輯的。這是什麼意思?你的意思是你有一些字符串不是代表數字的字符串嗎? –

回答

0

假設你有一個包含整數列,花車,和字符串,這些都是從一個文件中的字符串讀入,你就會有這樣的事情:

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