本文介绍了创建一个2D数组,其中包含来自数据框的2列,并循环获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个巨大的数据框,看起来像这样:
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
我想用轴 u_id
和 i_id
创建一个数组,值是 1
(如果 u_id
具有 i_id
),否则具有 0
.
像这样:
I want to create an array with the axes u_id
and i_id
and the value is 1
(if u_id
has the i_id
) and 0
otherwise.
Like that:
0 1 2 3
0 1 1 1 0
1 0 0 1 1
我用以下方法创建了数组:
I created the array with:
df_neu = np.full(df[['u_id', 'i_id']].nunique(), 0)
但是现在我不知道如何覆盖 0
.
but now I don't know how to overwrite 0
.
推荐答案
我认为这
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
我的假设是您的原始DataFrame名为 df
.
My assumption is that your original DataFrame is named df
.
如果要摆脱 u_id
索引:
df_neu.reset_index(drop=True, inplace=True)
0 1 2 3
0 1 1 1 0
1 0 0 1 1
或一个没有移调的:
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)
这篇关于创建一个2D数组,其中包含来自数据框的2列,并循环获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!