如何使用另一个数据框的列值生成数据框

4

我正在处理一个数据集,它在下面的数据框中。

#print(old_df)
   col1 col2 col3
0   1   10  1.5
1   1   11  2.5
2   1   12  5,6
3   2   10  7.8
4   2   24  2.1
5   3   10  3.2
6   4   10  22.1
7   4   11  1.3
8   4   89  0.5
9   4   91  3.3

我正在尝试生成另一个数据框,其中包含所选的col1值作为索引,所选的col2值作为列,并分配相应的col3值。
例如:
selected_col1 = [1,2]
selected_col2 = [10,11,24]

新数据框应该看起来像:
#print(selected_df)
     10     11     24
1    1.5    2.5    Nan
2    7.8    Nan    2.1

我已经尝试过以下方法

selected_col1 = [1,2]
selected_col2 = [10,11,24]
selected_df =pd.DataFrame(index=selected_col1,columns=selected_col2) 
for col1_value in selected_col1:
    for col2_value in selected_col2:
        qry = 'col1 == {} & col2 == {}'.format(col1_value,col2_value)
        col3_value = old_df.query(qry).col3.values
        if(len(col3_value) > 0):
            selected_df.at[col1_value,col2_value] = col3_value[0]

但是我的数据框大约有2000万行,这种蛮力方法需要很长时间。有比这更好的方法吗?

1个回答

6

首先使用 Series.isin 过滤出两列中的会员,通过按位 AND 链接两列,然后使用 DataFrame.pivot

df = df[df['col1'].isin(selected_col1) & df['col2'].isin(selected_col2)]

df = df.pivot('col1','col2','col3')
print (df)
col2   10   11   24
col1               
1     1.5  2.5  NaN
2     7.8  NaN  2.1

如果在筛选后的 col1 中有一些与 col2 重复的对,可以使用 DataFrame.pivot_table 进行处理:

df = df.pivot_table(index='col1',columns='col2',values='col3', aggfunc='mean')

编辑:

如果使用 | 进行按位 OR 运算,会得到不同的输出:

df = df[df['col1'].isin(selected_col1) | df['col2'].isin(selected_col2)]

df = df.pivot('col1','col2','col3')
print (df)
col2    10   11   12   24
col1                     
1      1.5  2.5  5,6  NaN
2      7.8  NaN  NaN  2.1
3      3.2  NaN  NaN  NaN
4     22.1  1.3  NaN  NaN

我遇到了以下错误:ValueError: Unstacked DataFrame is too big, causing int32 overflow\n 顺便说一下,我在初始化新的数据框时使用了“|”而不是“&”。 - Satheesh K
@SatheeshK - 不幸的是,错误意味着数据非常大,请问 selected_col1selected_col2 列表的长度是多少? - jezrael
我只使用 | 表示或。len(selected_col1)= 1894len(selected_col2)= 8546 - Satheesh K
@SatheeshK - 编辑答案并说明其中的区别。 - jezrael
1
@SatheeshK - 如果我理解正确的话,过滤后只剩下几行数据。这就是出现奇怪错误的原因,因为数据框很大。还有一件事 - 你可以尝试升级到最新的pandas版本,也许会有所帮助。 - jezrael
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接