python - 如何在 Python 中融化或取消堆叠数据帧?

标签 python pandas dataframe

我有一个想要融化的数据框。这是输入:

col1    col2    col3    col4    col5
file1  text_0  text_1  text_2        
file2  text_0  text_1  text_2  text_3
file3  text_0  

这是输出:

col1  col2
file1 text_0
file1 text_1
file1 text_2
file2 text_0
file2 text_1
file2 text_2
file2 text_3
file3 text_0 

最佳答案

使用DataFrame.melt首先,然后通过 query 过滤掉空字符串最后删除列变量:

df1 = (df.melt('col1', var_name='col2')
         .query("value != ''")
         .sort_values('col1')
         .drop('col2', axis=1))

print (df1)
     col1   value
0   file1  text_0
3   file1  text_1
6   file1  text_2
1   file2  text_0
4   file2  text_1
7   file2  text_2
10  file2  text_3
2   file3  text_0

关于python - 如何在 Python 中融化或取消堆叠数据帧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59427896/

相关文章:

python - Pandas :在两次之间生成日期时间并将结果作为数据框中的新行传递

python - 如何使用wxpython和rpy2显示图像?

python - groupby中的pandas聚合函数-默认选项?

python - 如何使用 python pandas 通过多索引获取值?

python - Pandas:在数据框中创建一个新列,其中的值是根据现有列计算得出的,即。计算最大值

python - 寻找一种更快的方法在包含另一列行中的字典值的数据框中创建新列

python - 在所有包中搜索特定函数

python - 我可以将计数器反转为没有倍数的列表列表吗?

python - 检查 pandas 数据帧的最后一行是否满足条件的最佳方法是什么?

python - 将 pyodbc.rows 列表转换为 pandas Dataframe 需要很长时间