文字列を含む Pandas データフレームをピボットする - 「集計する数値型がありません」というエラー 質問する

文字列を含む Pandas データフレームをピボットする - 「集計する数値型がありません」というエラー 質問する

このエラーについては多くの質問がありますが、調べてみてもまだ解決策が見つからず、頭を整理できていません。文字列を含むデータ フレームをピボットして、行データを列にしようとしていますが、今のところうまくいきません。

私のDFの形状

<class 'pandas.core.frame.DataFrame'>
Int64Index: 515932 entries, 0 to 515931
Data columns (total 5 columns):
id                 515932 non-null object
cc_contact_id      515932 non-null object
Network_Name       515932 non-null object
question           515932 non-null object
response_answer    515932 non-null object
dtypes: object(5)
memory usage: 23.6+ MB

サンプルフォーマット

id  contact_id  question    response_answer
16  137519  2206    State   Ca
17  137520  2206    State   Ca
18  137521  2206    State   Ca
19  137522  2206    State   Ca
20  137523  2208    City    Lancaster
21  137524  2208    City    Lancaster
22  137525  2208    City    Lancaster
23  137526  2208    City    Lancaster
24  137527  2208    Trip_End Location   Home
25  137528  2208    Trip_End Location   Home
26  137529  2208    Trip_End Location   Home
27  137530  2208    Trip_End Location   Home

私が方向転換したいこと

id  contact_id      State   City       Trip_End Location
16  137519  2206    Ca      None       None None
20  137523  2208    None    Lancaster  None None
24  137527  2208    None    None       None Home
etc. etc. 

どこ質問値は列になり、回答対応する列にあり、IDを保持する

私が試したこと

unified_df = pd.DataFrame(unified_data, columns=target_table_headers, dtype=object)

pivot_table = unified_df.pivot_table('response_answer',['id','cc_contact_id'],'question')
# OR
pivot_table = unified_df.pivot_table('response_answer','question')

DataError: 集計する数値型がありません

文字列値を含むデータフレームをピボットする方法は何ですか?

ベストアンサー1

のデフォルトaggfuncpivot_tableでありnp.sum、文字列をどう処理すればよいかがわからず、インデックスが何であるべきかが適切に示されていません。次のようなものを試してみてください:

pivot_table = unified_df.pivot_table(index=['id', 'contact_id'],
                                     columns='question', 
                                     values='response_answer',
                                     aggfunc=lambda x: ' '.join(x))

これにより、ペアごとに 1 行が明示的に設定され、値id, contact_idのセットが でピボットされます。 は、生データに同じ質問に対する複数の回答がある場合に、それらをスペースで連結することを保証します。 の構文は、pandas のバージョンによって異なる場合があります。response_answerquestionaggfuncpivot_table

簡単な例を以下に示します。

In [24]: import pandas as pd

In [25]: import random

In [26]: df = pd.DataFrame({'id':[100*random.randint(10, 50) for _ in range(100)], 'question': [str(random.randint(0,3)) for _ in range(100)], 'response': [str(random.randint(100,120)) for _ in range(100)]})

In [27]: df.head()
Out[27]:
     id question response
0  3100        1      116
1  4500        2      113
2  5000        1      120
3  3900        2      103
4  4300        0      117

In [28]: df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 100 entries, 0 to 99
Data columns (total 3 columns):
id          100 non-null int64
question    100 non-null object
response    100 non-null object
dtypes: int64(1), object(2)
memory usage: 3.1+ KB

In [29]: df.pivot_table(index='id', columns='question', values='response', aggfunc=lambda x: ' '.join(x)).head()
Out[29]:
question        0        1    2        3
id
1000      110 120      NaN  100      NaN
1100          NaN  106 108  104      NaN
1200      104 113      119  NaN      101
1300          102      NaN  116  108 120
1400          NaN      NaN  116      NaN

おすすめ記事