【问题标题】:How to be able to concatenate the values of a column with the name of the other columns in a DataFrame如何能够将列的值与 DataFrame 中其他列的名称连接起来
【发布时间】:2021-01-01 08:17:42
【问题描述】:

如何能够将名为“ITEM”的列的值与其他列的名称连接起来,从而创建新列。

如果我有这样的数据框:

import pandas as pd

df = pd.DataFrame({
    'ITEM': ['Item1', 'Item2', 'Item3'],
    'Variable1': [1,1,2],
    'Variable2': [2,1,3],
    'Variable3':[3,2,4]

})
df

我需要转换这个数据框:

enter image description here

在那个数据框上:

enter image description here

【问题讨论】:

  • 请展示您的尝试。您可以使用 pandas 函数(例如 concat/join/etc)或编写两个 for 循环来遍历列和索引。
  • 为什么发数据图片,贴实际数据,格式化成代码

标签: python pandas dataframe concatenation


【解决方案1】:
import pandas as pd

df = pd.DataFrame({
    'ITEM': ['Item1', 'Item2', 'Item3'],
    'Variable1': [1,1,2],
    'Variable2': [2,1,3],
    'Variable3':[3,2,4]

})

df = pd.melt(df, id_vars='ITEM',value_vars=['Variable1','Variable2','Variable3'])
df['title'] = df['variable']+'_'+df['ITEM']
df = df[['title','value']].T
df.columns = df.iloc[0]
df = df[1:]

【讨论】:

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