Python Pandas 插入带有列值的新行

标签 python excel pandas

我正在编写一个 python 脚本来清理我们从 Qualtrics 收到的用于创业竞赛的 CSV 文件。

到目前为止,我已经对数据进行了切片,并使用 Pandas 将其写回到 Excel 文件中。但是,我有一些列需要用来创建新行。 例如,对于每个团队提交,我们有

       Team Name    Nb of teammates   Team Leader One    Team Leader Two      
 1       x                2                Joe              Joey
 2       y                1                Jack
 ...

我需要回去

       Team Name    Nb of teammates   Team Leader          
 1       x                2                Joe             
 2                                         Joey                 
 3       y                1                Jack
 ...

这是我所拥有的真实数据的一个非常简化的示例,因为有更多的列,但我想知道如何在 Pandas/Python 中做到这一点。

我知道关于 Inserting Row 的这些讨论和 Indexing: Setting with enlargement ,但我不知道该怎么办。

感谢您的帮助!

最佳答案

你可以使用熔体:

#set up frame
df =pd.DataFrame({'Team Name':['x','y'], 'Nb of teammates':[2,1], 'Team Leader One':['Joe','Jack'],'Team Leader Two':['Joey',None]})

熔化框架:

pd.melt(df,id_vars=['Team Name','Nb of teammates'],value_vars=['Team Leader One','Team Leader Two']).dropna()

返回:

   Team Name    Nb of teamates  variable            value
0   x           2               Team Leader One     Joe
1   y           1               Team Leader One     Jack
2   x           2               Team Leader Two     Joey

关于Python Pandas 插入带有列值的新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28688226/

相关文章:

python - 获取方向 pytesseract Python3

python - 尝试训练 Keras 模型时出现“资源耗尽”内存错误

python - 仅打印 Python 中特定键的字典术语的值

excel - 无法使用SSIS打开excel文件,除非手动保存

python - 使用 Python 转换为 CSV 的文本文件与使用 Excel 转换不同

html - 从网页单击 Excel 图标的 VBA 代码

python - 在 Pandas DataFrame 中查找和计算字符串值

python - 如何迭代不区分大小写的已排序字典项?

python - 二维日期时间分组依据

python - Pandas :数据透视表