【问题标题】:Dataframe convert value in columns into colums name数据框将列中的值转换为列名
【发布时间】:2021-03-06 17:34:41
【问题描述】:

我想将名称列中的名称值转换为名称列,并将其余值转换为一行。我尝试使用 Pivot,但不能很好地解决我的问题。

你有什么想法吗?

输入:

dict_value = {
'Name' : ['Pierre', 'Paul'],
'Age' : [10,20],
'City' : ['NY', 'PR']}

df = pd.DataFrame(dict_value)

输出:

【问题讨论】:

    标签: python pandas pivot transpose


    【解决方案1】:

    您可以使用df.stack,然后将MultiIndex 展平。然后使用.to_frame 并转置。

    out = df.set_index('Name').stack()
    out.index = out.index.map('.'.join)
    out.to_frame().T
    
      Pierre.Age Pierre.City Paul.Age Paul.City
    0         10          NY       20        PR
    

    【讨论】:

    • @FloCp 很高兴为您提供帮助。 ;)
    【解决方案2】:

    我相信通过使用 set_indexunstack 你可能会得到你想要的解决方案。你可以查看Pandas convert dataframe values to column names

    【讨论】:

      猜你喜欢
      • 2020-03-16
      • 1970-01-01
      • 2021-08-24
      • 2020-01-03
      • 2017-10-17
      • 1970-01-01
      • 2014-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多