2016-08-18 4 views
1

で私はこのようにその情報が表示されますパンダにおけるデータフレームがあります:データ[「高さ」]今の反復カスタム機能

  Player  Year Height 
1  Stephen Curry 2015-16 6-3 
2 Mirza Teletovic 2015-16 6-10 
3  C.J. Miles 2015-16 6-7 
4 Robert Covington 2015-16 6-9 

は、文字列としてその値を格納し、私はこれらの値を整数としてインチ・ストアに変換して、さらに計算したいと思います。

私はPandasのドキュメントに記載されているものを含めて、いくつかのアプローチを試しましたが、役に立たないものです。

最初の試行

def true_height(string): 
    new_str = string.split('-') 
    inches1 = new_str[0] 
    inches2 = new_str[1] 

    inches1 = int(inches1)*12 
    inches2 = int(inches2) 

    return inches1 + inches2 

あなたは

true_height(data.iloc[0, 2]) 

を実行した場合はそれが正しい答え、75を返します。

new_str = string.**str**.split('-') 

そして走っ:

data['Height'].apply(true_height(data['Height'])) 

をし、次のエラーメッセージました:

int() argument must be a string or a number, not 'list' 

を、私はこのコード行を変更し、シリーズ全体でそれを実行する

私はその後、forループを使って試してみると、そのトリックを解決するかもしれないと思ったので、元の式をこれに変更しました:

def true_height(strings): 
for string in strings: 
    new_str = string.split('-') 
    inches1 = new_str[0] 
    inches2 = new_str[1] 

    inches1 = int(inches1)*12 
    inches2 = int(inches2) 

    return inches1 + inches2 

そして今、私は次のエラーを取得する:

'int' object is not callable 

私は実行すると:

data['Height'].apply(true_height(data['Height'])) 

私は少し困惑。どんな助けもありがとう。ありがとうございました。

あなたはそれがリストに分割されます後 Height列に適用されます使用して、変換のためにそれにラムダ関数を渡すことができ
+0

'def true_height(strings):'行の後ろにインデントしてください。 –

答えて

1

df['Height'] = df.Height.str.split("-").apply(lambda x: int(x[0]) * 12 + int(x[1])) 

df 
#    Player  Year Height 
# 1 Stephen Curry 2015-16  75 
# 2 Mirza Teletovic 2015-16  82 
# 3  C.J. Miles 2015-16  79 
# 4 Robert Covington 2015-16  81 

またはapplyであなたの最初に定義されtrue_height機能(第一の試み)を使用します。

df['Height'] = df.Height.apply(true_height) 

applyはパラメータとして関数を受け取るので、df.Heightを関数に渡す必要はありません。

+0

私はこれをまだ答えたとは言えませんが、とても魅力的に働いてくれてありがとう、ありがとう。私はラムダ表記法をあまり使用していませんが、これは非常に役に立ちました。 1つの質問:df ['Height']をある場所に、df.Heightを別の場所で使用した特定の理由はありますか? ありがとうございます。 –

+0

特別な理由はありません。私はちょうど '.Height'が少しタイピングを保存することを発見します。ただし、データフレームに存在しない新しい変数に割り当てるときは使用できません。だから私は左側に '['']'を使わなければなりません。それは習慣になります。 – Psidom

1
df['feet'], df['inches'] = zip(*df.Height.str.split('-')) 

df['feet'] = df.feet.astype(int) 
df['inches'] = df.inches.astype(float) 
df['height_inches'] = df.feet * 12 + df.inches 

>>> df 
       Player  Year Height feet inches height_inches 
1 Stephen  Curry 2015-16 6-3  6  3    75 
2 Mirza Teletovic 2015-16 6-10  6  10    82 
3 C.J.   Miles 2015-16 6-7  6  7    79 
4 Robert Covington 2015-16 6-9  6  9    81