Skip to content

BUG: DataFrame.melt gives unexpected result when column "value" already exists #34731

Closed
@erfannariman

Description

@erfannariman
  • I have checked that this issue has not already been reported.

  • I have confirmed this bug exists on the latest version of pandas.

  • (optional) I have confirmed this bug exists on the master branch of pandas.


Code Sample, a copy-pastable example

df = pd.DataFrame({'col':list('ABC'),
                   'value':range(10,16,2)})
print(df, '\n')

dfm = df.melt(id_vars='value')

print(dfm)

  col  value
0   A     10
1   B     12
2   C     14 

  value variable value
0     A      col     A
1     B      col     B
2     C      col     C

Problem description

When the column value already exists, and we set it as index with id_vars it copies the value column of the melted dataframe and does not set the "old" value column of the original dataframe as id_vars

Expected Output

# note change of column name 'val' instead of 'value'
df = pd.DataFrame({'col':list('ABC'),
                   'val':range(10,16,2)})

dfm = df.melt(id_vars='val')

print(dfm)
   val variable value
0   10      col     A
1   12      col     B
2   14      col     C

Output of pd.show_versions()

INSTALLED VERSIONS

commit : None
python : 3.8.3.final.0
python-bits : 64
OS : Darwin
OS-release : 19.5.0
machine : x86_64
processor : i386
byteorder : little
LC_ALL : None
LANG : None
LOCALE : None.UTF-8

pandas : 1.0.3
numpy : 1.18.1
pytz : 2020.1
dateutil : 2.8.1
pip : 20.0.2
setuptools : 47.1.1.post20200604
Cython : None
pytest : None
hypothesis : None
sphinx : None
blosc : None
feather : None
xlsxwriter : None
lxml.etree : None
html5lib : None
pymysql : None
psycopg2 : None
jinja2 : 2.11.2
IPython : 7.13.0
pandas_datareader: None
bs4 : None
bottleneck : None
fastparquet : None
gcsfs : None
lxml.etree : None
matplotlib : None
numexpr : None
odfpy : None
openpyxl : None
pandas_gbq : None
pyarrow : None
pytables : None
pytest : None
pyxlsb : None
s3fs : None
scipy : None
sqlalchemy : None
tables : None
tabulate : None
xarray : None
xlrd : None
xlwt : None
xlsxwriter : None
numba : None

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugError ReportingIncorrect or improved errors from pandasReshapingConcat, Merge/Join, Stack/Unstack, Explode

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions