簡體   English   中英

如何在Python Pandas中將dtype從object轉換為int?

[英]How to convert a dtype from object to int in Python pandas?

我有一個數據文件,當我在df.dtypes上運行df.dtypes時,它表示該類型是一個對象,但要繪制它需要是一個integerfloatdouble float等。數據實際上由三列數字組成, 像這樣:

123 12345 0.9484 
123 12345 0.8746 
123 12345 0.4838 
123 12345 0.4837 

如何轉換數據以便可以使用pandas進行繪制?

我認為您可以使用帶有參數的read_csvsep='\\s+' (任意空格)和engine='python' (因為警告):

import pandas as pd
import io

temp=u"""Day Time Usage
123 12345 0.9484
123 12345 0.8746
123 12345 0.4838
123 12345 0.4837"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), sep='\s+', engine='python')

print df
   Day   Time   Usage
0  123  12345  0.9484
1  123  12345  0.8746
2  123  12345  0.4838
3  123  12345  0.4837

print df.dtypes
Day        int64
Time       int64
Usage    float64
dtype: object

print df.index
Int64Index([0, 1, 2, 3], dtype='int64')

pandas.read_csv數據類型轉換

這個答案假設你有matplotlib庫,你在iPython中計算,你的文件是csv -ish。

%matplotlib inline
import pandas as pd
from cStringIO import StringIO

fake_csv = '''123 12345 0.9484
123 12345 0.8746
123 12345 0.4838
123 12345 0.4837'''

# Create data frame, fake csv for example only
# normally you would use pd.read_csv('/path/to/file.csv', ...)
df = pd.read_csv(StringIO(fake_csv), sep='\s+', header=None)

print 'DataFrame:\n{}\n\nData Types:\n{}'.format(df, df.dtypes)

df.plot()

DataFrame:
     0      1       2
0  123  12345  0.9484
1  123  12345  0.8746
2  123  12345  0.4838
3  123  12345  0.4837

Data Types:
0      int64
1      int64
2    float64
dtype: object

df圖

注意:最后一個dtype:objectdf.dtypes Series的數據類型,而不是df類型的數據類型。

暫無
暫無

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

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