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_stuff
:ValueError: Shape of passed values is (4, 2), indices imply (4, 3)
はapply
関数は次のコードで実行されるときに発生します私は、各行に多くの異なる列を使用し、複数の新しい列を返すことを適用しています。
しかし、上記の例では、データフレームのshape
に関連してこのValueError
がまだ修正されていません。
既存の列から計算できる複数の新しい列を(各行に対して)作成する方法はありますか?