python - 我想将数据框的行附加为列

标签 python pandas dataframe rows col

我有几个小数据框,例如:

name   x   y  z
A      1   2  3
A      1   23  4
A      3    5   6
B       0    2  3

我想附加所有“A”,以便获得此数据框

name    x    y   z   x2   y2 z2    x3   y3   z3
A         1   2  3    1    23 4    3    5     6
B         0  2  3    NaN-------------------> NaN

如有任何帮助,我们将不胜感激,如果上述表格间隔不正确,我们深表歉意

最佳答案

更像是通过cumcount创建 key 后的pivot问题——我在这里使用unstack

df['Newkey']=df.groupby('name').cumcount()+1
yourdf=df.set_index(['name','Newkey']).unstack().sort_index(level=1,axis=1)
yourdf.columns=yourdf.columns.map('{0[0]}{0[1]}'.format)
yourdf
Out[20]: 
       x1   y1   z1   x2    y2   z2   x3   y3   z3
name                                              
A     1.0  2.0  3.0  1.0  23.0  4.0  3.0  5.0  6.0
B     0.0  2.0  3.0  NaN   NaN  NaN  NaN  NaN  NaN

关于python - 我想将数据框的行附加为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55330648/

相关文章:

python - 凯拉斯 + tensorflow : “module ' tensorflow' has no attribute 'merge_all_summaries' '”

python - 峰度函数在 python 和 matlab 中显示不同的值

python - 如果某些行不存在于其他数据帧中,Pandas 连接两个数据帧并保留一个数据集中的数据

python - 在 pandas 数据框中旋转一列并创建 4 个新列

python - 如果在类型列表的单元格值中找到字符串,如何根据条件删除 pandas 数据框中的行?

python - 指定列上的 Numpy 总和

python - 带子图的 Matplotlib bbox_to_anchor

python - 访问散点图的 matplotlib 对象

python - 在数据框中添加新行,并有条件分割前一行

python - pandas.read_csv 函数带有 chunksize 选项的奇怪索引机制