【问题标题】:Python Pandas inserting new rows with colums valuesPython Pandas 使用列值插入新行
【发布时间】:2015-02-24 04:34:28
【问题描述】:

我正在编写一个 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 RowIndexing: Setting with enlargement 上的这些讨论,但我不知道该怎么办。

感谢您的帮助!

【问题讨论】:

  • 杨从哪里来?
  • 我的坏杨无所谓

标签: python excel pandas


【解决方案1】:

你可以使用融化:

#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

【讨论】:

  • 那我想我可以按团队名称排序以重新排列它们?
猜你喜欢
  • 2014-01-23
  • 2016-01-13
  • 2023-03-31
  • 1970-01-01
  • 2020-11-01
  • 1970-01-01
  • 2015-10-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多