adplus-dvertising

How to convert list to data frame

Asked 2 days ago
Viewed 18 times

this is code that I have


import pandas as pd

data = [[1,"credit"],[1,"cash"],[1,"credit"],[2,"credit"],[2,"credit"],[2,"credit"],[3,"credit"],[3,"credit"],[3,"credit"]]
df = pd.DataFrame(data, columns=['account_id','type'])

final={}
sym = df.groupby('account_id')
for symbol,groups in sym:
    final[symbol] = groups["type"].value_counts().values[0]

print(final)

when I use

df= pd.DataFrame (final, columns = ['account_id', 'type'])

it shows only | account_id | type |

asked 2 days ago

Correct Answer

if you want count 'credit type' by account id, use this code

data = [[1, "credit"], [1, "cash"], [1, "credit"], [2, "credit"], [
    2, "credit"], [2, "credit"], [3, "credit"], [3, "credit"], [3, "credit"]]
df = pd.DataFrame(data, columns=['account_id', 'type'])
df.groupby('account_id')['type'].agg(
    lambda x: (x == df['type'].unique()[0]).sum())

or

df[df['type'] == df['type'].unique()[0]].groupby('account_id')['type'].count()

df['type'].unique()[0] can replace by 'credit'

answered 2 days ago