現在、さまざまな行の内容に基づいて、特定の行の統計的検定を実装しようとしています。次の画像のデータフレームを考えます。
DataFrame列「テンプレート」に同じ文字列を持つデータフレームのすべての列を考慮に入れる関数に基づいて、新しい列を作成したいと思います。
たとえば、この場合、テンプレート「[Are | Off]」の行が2つあり、それらの行ごとに、「クリック数」、「インプレッション数」、「コンバージョン数」に基づいて新しい列に要素を作成する必要があります。両方の行の "。
この問題にどのようにアプローチするのが最善ですか?
PS:私がプロのコードではないことに気付くかもしれないので、私が問題を説明している方法について事前に謝罪します:Dしかし、私は本当にあなたの助けに感謝します!
これを私がExcelで解決した式は次のとおりです。
これは一般的すぎるかもしれませんが、テンプレート名に応じて異なることを行う必要がある場合は、ある種の関数マップを使用します。
import pandas as pd
import numpy as np
import collections
n = 5
template_column = list(['are|off', 'are|off', 'comp', 'comp', 'comp|city'])
n = len(template_column)
df = pd.DataFrame(np.random.random((n, 3)), index=range(n), columns=['Clicks', 'Impressions', 'Conversions'])
df['template'] = template_column
# Use a defaultdict so that you can define a default value if a template is
# note defined
function_map = collections.defaultdict(lambda: lambda df: np.nan)
# Now define functions to compute what the new columns should do depending on
# the template.
function_map.update({
'are|off': lambda df: df.sum().sum(),
'comp': lambda df: df.mean().mean(),
'something else': lambda df: df.mean().max()
})
# The lambda functions are just placeholders. You could do whatever you want in these functions... for example:
def do_special_stuff(df):
"""Do something that uses rows and columns...
you could also do looping or whatever you want as long
as the result is a scalar, or a sequence with the same
number of columns as the original template DataFrame
"""
crazy_stuff = np.prod(np.sum(df.values,axis=1)[:,None] + 2*df.values, axis=1)
return crazy_stuff
function_map['comp'] = do_special_stuff
def wrap(f):
"""Wrap a function so that it returns an updated dataframe"""
def wrapped(df):
df = df.copy()
new_column_data = f(df.drop('template', axis=1))
df['new_column'] = new_column_data
return df
return wrapped
# wrap all the functions so that each template has a function defined that does
# the correct thing
series_function_map = {k: wrap(function_map[k]) for k in df['template'].unique()}
# throw everything back together
new_df = pd.concat([series_function_map[label](group)
for label, group in df.groupby('template')],
ignore_index=True)
# print your shiny new dataframe
print(new_df)
結果は次のようになります。
Clicks Impressions Conversions template new_column
0 0.959765 0.111648 0.769329 are|off 4.030594
1 0.809917 0.696348 0.683587 are|off 4.030594
2 0.265642 0.656780 0.182373 comp 0.502015
3 0.753788 0.175305 0.978205 comp 0.502015
4 0.269434 0.966951 0.478056 comp|city NaN
それが役に立てば幸い!
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加