2017-08-17 2 views
1

パンダデータフレームの各行に対して複数の計算列を返す必要があります。複数の新しい列を返す関数を適用するときのパンダシェイプの問題

このエラー:

import pandas as pd 

my_df = pd.DataFrame({ 
    'datetime_stuff': ['2012-01-20', '2012-02-16', '2012-06-19', '2012-12-15'], 
    'url': ['http://www.something', 'http://www.somethingelse', 'http://www.foo', 'http://www.bar' ], 
    'categories': [['foo', 'bar'], ['x', 'y', 'z'], ['xxx'], ['a123', 'a456']], 
}) 

my_df['datetime_stuff'] = pd.to_datetime(my_df['datetime_stuff']) 
my_df.sort_values(['datetime_stuff'], inplace=True) 

print(my_df.head()) 

def calculate_stuff(row): 
    if row['url'].startswith('http'): 
    categories = row['categories'] if type(row['categories']) == list else [] 
    calculated_column_x = row['url'] + '_other_stuff_' 
    else: 
    calculated_column_x = None 
    another_column = 'deduction_from_fields' 
    return calculated_column_x, another_column 

print(my_df.shape) 

my_df['calculated_column_x'], my_df['another_column'] = zip(*my_df.apply(calculate_stuff, axis=1)) 

私が働いているデータフレームの各行は、上記の例よりも複雑であり、そして機能calculate_stuffValueError: Shape of passed values is (4, 2), indices imply (4, 3)apply関数は次のコードで実行されるときに発生します私は、各行に多くの異なる列を使用し、複数の新しい列を返すことを適用しています。

しかし、上記の例では、データフレームのshapeに関連してこのValueErrorがまだ修正されていません。

既存の列から計算できる複数の新しい列を(各行に対して)作成する方法はありますか?

答えて

1

適用されている関数からリストまたはタプルを返すと、pandasは適用したデータフレームに戻します。代わりに、系列を返します。


・再構成コード

my_df = pd.DataFrame({ 
    'datetime_stuff': ['2012-01-20', '2012-02-16', '2012-06-19', '2012-12-15'], 
    'url': ['http://www.something', 'http://www.somethingelse', 'http://www.foo', 'http://www.bar' ], 
    'categories': [['foo', 'bar'], ['x', 'y', 'z'], ['xxx'], ['a123', 'a456']], 
}) 

my_df['datetime_stuff'] = pd.to_datetime(my_df['datetime_stuff']) 
my_df.sort_values(['datetime_stuff'], inplace=True) 

def calculate_stuff(row): 
    if row['url'].startswith('http'): 
    categories = row['categories'] if type(row['categories']) == list else [] 
    calculated_column_x = row['url'] + '_other_stuff_' 
    else: 
    calculated_column_x = None 
    another_column = 'deduction_from_fields' 

    # I changed this VVVV 
    return pd.Series((calculated_column_x, another_column), ['calculated_column_x', 'another_column']) 

my_df.join(my_df.apply(calculate_stuff, axis=1)) 

    categories datetime_stuff      url     calculated_column_x   another_column 
0 [foo, bar]  2012-01-20  http://www.something  http://www.something_other_stuff_ deduction_from_fields 
1  [x, y, z]  2012-02-16 http://www.somethingelse http://www.somethingelse_other_stuff_ deduction_from_fields 
2   [xxx]  2012-06-19   http://www.foo   http://www.foo_other_stuff_ deduction_from_fields 
3 [a123, a456]  2012-12-15   http://www.bar   http://www.bar_other_stuff_ deduction_from_fields 
関連する問題