Pandas Dataframe 将多行和多列转换为单行 [key] 和 column[key]

Pandas dataframe convert multiple rows and columns to single row[key] and column[key]

提问人:Shekar Tippur 提问时间:3/20/2021 最后编辑:desertnautShekar Tippur 更新时间:3/20/2021 访问量:283

问:

我有一个 pandas 数据帧,我需要将其转换为带有 . 我拥有的数据帧是密集形式User ID, MovieId, Rating

import numpy as np
import pandas as pd
d={'user_id':[1,2], 'col1': [1, np.nan], 'col2': [np.nan, 4], 'col3': [np.nan, 3]}
df=pd.DataFrame(data=d)

我想要它的形式:

user_id feature value
0   1.0 col1    1.0
1   1.0 col2    NaN
2   1.0 col3    NaN
3   2.0 col1    NaN
4   2.0 col2    4.0
5   2.0 col3    3.0

我写了一个小函数来实现这一点:

def func(df_x):
    
    df_temp=pd.DataFrame()
    for index, row in df_x.iterrows():
        for cols in df_x.columns:
            if 'user_id' in cols:
                continue
            d_n={'user_id':row['user_id'], 'feature': cols, 'value': row[cols]}
            df_temp = df_temp.append(pd.DataFrame(d_n, index=[0]), ignore_index=True)

    return df_temp

这似乎适用于小型数据集,但对于较大的数据集,这种方法似乎需要很长时间。对于我拥有的 14500 * 60 数据集,笔记本电脑上的单元格在运行了一夜后(在我的 16GB 笔记本电脑上)完成执行。 您能建议一个最佳的方法来解决这个问题吗?

python-3.x pandas 数据帧

评论

0赞 desertnaut 3/20/2021
不是问题,请不要向不相关的标签发送垃圾邮件(已删除)。machine-learning

答:

0赞 BENY 3/20/2021 #1

然后尝试meltsort_values

out = df.melt('user_id').sort_values('user_id')
Out[397]: 
   user_id variable  value
0        1     col1    1.0
2        1     col2    NaN
4        1     col3    NaN
1        2     col1    NaN
3        2     col2    4.0
5        2     col3    3.0

评论

0赞 Shekar Tippur 3/20/2021
谢谢。现在尝试。
1赞 Shekar Tippur 3/20/2021
这真是太棒了。成功了。谢谢。它不允许我立即接受答案。将等待并接受答案。再次感谢。
0赞 BENY 3/20/2021
@ShekarTippur没问题,祝您编码愉快