【问题标题】:How to reshape pandas dataframe only line and add value [duplicate]如何仅重塑熊猫数据框线并添加价值[重复]
【发布时间】:2019-11-22 09:40:44
【问题描述】:

我有这个代码作为输入(我会为多个数据帧多次这样做,所以我的代码在循环中)


v="S"
df_a = pd.DataFrame({ 'Type1': ['A'],'Type2': ['B'],'Type3': ['C'],'Type4': ['D']})
df_a

Output : 

    Type1   Type2   Type3   Type4
0   A       B       C       D


我需要这个


Output : 

    V   Col     Val
0   S   Type1   A
1   S   Type2   B
2   S   Type3   C
3   S   Type4   D


谢谢

【问题讨论】:

  • df_a.melt(var_name='Col', value_name='Val').assign(V=v)

标签: python pandas dataframe reshape


【解决方案1】:

试试这个:

v="S"
df_a = pd.DataFrame({ 'V': ['S'],'Col': ['Type1'],'Val': ['A']},
               { 'V': ['S'],'Col': ['Type2'],'Val': ['B']},
               { 'V': ['S'],'Col': ['Type3'],'Val': ['C']},
               { 'V': ['S'],'Col': ['Type4'],'Val': ['D']})


 print(df_a)

之后我们使用命令 df.append 添加行,这里是一个示例: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.append.html

【讨论】:

    【解决方案2】:

    以下语句将解决您的目的:

    df_a = df_a.melt()
    df_a['V'] = 'S'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多