Create A 2D Array With 2 Columns From A Dataframe And Loop For Value
I have a huge dataframe which looks like this: u_id i_id 0 55218 0 1 55218 2 2 55218 1 3 55222 2 4 55222 3 I want to create a
Solution 1:
Please try:
df = df.groupby('u_id')['i_id'].apply(list).reset_index()
def fill(x):
for val in x.i_id:
df_un[x.name,val] = 1
df.apply(lambda x: fill(x), axis=1)
print(df_un)
[[1 1 1 0]
[0 0 1 1]]
Solution 2:
I think that this
columns = sorted(set(df['i_id'].values))
df_neu = pd.DataFrame({key: [1 if c in group['i_id'].values else 0
for c in columns]
for key, group in df.groupby('u_id')},
index=columns).T
essentially leads to your expected result:
0 1 2 3
55218 1 1 1 0
55222 0 0 1 1
My assumption is that your original DataFrame is named df.
If you want to get rid of the u_id index:
df_neu.reset_index(drop=True, inplace=True)
0 1 2 3
0 1 1 1 0
1 0 0 1 1
Or a without the transposing:
columns = sorted(set(df['i_id'].values))
df_neu = pd.DataFrame([[1 if c in group['i_id'].values else 0
for c in columns]
for _, group in df.groupby('u_id')],
columns=columns)
Post a Comment for "Create A 2D Array With 2 Columns From A Dataframe And Loop For Value"