2017-03-09 6 views
1

このトピックに関するいくつかの質問を読んだことがありますが、何も私のためにはうまくいかないようです。URLをpandasデータフレームとして列名で読む(python3)

このページのデータ「http://archive.ics.uci.edu/ml/machine-learning-databases/statlog/heart/heart.dat」を特定の列名で検索したいとします。

私のコードですべてが単一の列にあるので、私は、データの列に名前を割り当てることはできません。以下、:

import pandas as pd 
import io 
import requests 
url="http://archive.ics.uci.edu/ml/machine-learningdatabases/statlog/heart/heart.dat" 
s=requests.get(url).content 
header_row = ['age','sex','chestpain','restBP','chol','sugar','ecg','maxhr','angina','dep','exercise','fluor','thal','diagnosis'] 
c=pd.read_csv(io.StringIO(s.decode('utf-8')), names=header_row) 
print(c) 

出力は次のとおりです。

 age sex chestpain \ 
0 70.0 1.0 4.0 130.0 322.0 0.0 2.0 109.0 0.0 2.4... NaN  NaN 
1 67.0 0.0 3.0 115.0 564.0 0.0 2.0 160.0 0.0 1.6... NaN  NaN 
2 57.0 1.0 2.0 124.0 261.0 0.0 0.0 141.0 0.0 0.3... NaN  NaN 
3 64.0 1.0 4.0 128.0 263.0 0.0 0.0 105.0 1.0 0.2... NaN  NaN 

私の目標を達成するためには何が必要ですか?

ありがとうございます!

+0

あなたは本当にURLですか?私はそれを開くと404エラーが表示されます –

+0

正しいURL https://archive.ics.uci.edu/ml/machine-learning-databases/statlog/heart/heart.dat –

答えて

1

入力したリンクにハイフンがありませんでした。私は私の答えでそれを修正しました。基本的にs文字列をutf-8にデコードしてから、\nに分割して各行を取得し、各行を空白に分割して各値を別々に取得する必要があります。これにより、パンダのデータフレームに変換できるデータセットのネストされたリスト表現が得られます。その後、カラム名を割り当てることができます。

import pandas as pd 
import io 
import requests 
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/statlog/heart/heart.dat" 
s = requests.get(url).content 
s = s.decode('utf-8') 
s_rows = s.split('\n') 
s_rows_cols = [each.split() for each in s_rows] 
header_row = ['age','sex','chestpain','restBP','chol','sugar','ecg','maxhr','angina','dep','exercise','fluor','thal','diagnosis'] 
c = pd.DataFrame(s_rows_cols, columns = header_row) 
c.head() 
+0

ありがとうございました!これが私の必要なものでした!宜しくお願いします!!! –

関連する問題