pandas - Built-in support for converting column names into values? -
does pandas have built-in support converting this
foo bar baz color texture 0 845 758 421 red creamy 1 259 512 405 red crunchy 2 784 304 477 green creamy 3 584 909 505 green crunchy 4 282 756 619 blue creamy 5 251 910 983 blue crunchy
to this
brand color texture votes 0 foo red creamy 845 1 foo red crunchy 259 2 foo green creamy 784 3 foo green crunchy 584 4 foo blue creamy 282 5 foo blue crunchy 251 6 bar red creamy 758 7 bar red crunchy 512 8 bar green creamy 304 9 bar green crunchy 909 10 bar blue creamy 756 11 bar blue crunchy 910 12 baz red creamy 421 13 baz red crunchy 405 14 baz green creamy 477 15 baz green crunchy 505 16 baz blue creamy 619 17 baz blue crunchy 983
?
in words: some of column headers have been converted values of new column brand
, , values under these columns have been placed in new column votes
.
(of course, names 'brand' , 'votes' of new columns cannot deduced original dataframe; they'd need provided additional data on top of original dataframe. also, 1 imagine additional information provided position of new columns among dataframe's columns.)
nb: don't implementing conversion simpler primitives. asking whether pandas has function it, , if so, it.
fwiw, here's code generate starting dataframe shown above:
import pandas import itertools import random color = ['red', 'green', 'blue'] texture = ['creamy', 'crunchy'] brand = ['foo', 'bar', 'baz'] random.seed(0) records = [tuple(random.randint(1, 10000) _ in brand) + p p in itertools.product(color, texture)] columns = brand + ['color', 'texture'] dataframe = pandas.dataframe.from_records(records, columns=columns)
you're looking melt
:
>>> pandas.melt(dataframe, id_vars=["color", "texture"], var_name="brand", value_name="votes") color texture brand votes 0 red creamy foo 6312 1 red crunchy foo 4243 2 green creamy foo 6635 3 green crunchy foo 5867 4 blue creamy foo 8269 5 blue crunchy foo 2290 6 red creamy bar 6891 7 red crunchy bar 8377 8 green creamy bar 4970 9 green crunchy bar 9559 10 blue creamy bar 2282 11 blue crunchy bar 1554 12 red creamy baz 664 13 red crunchy baz 7962 14 green creamy baz 7809 15 green crunchy baz 3579 16 blue creamy baz 4618 17 blue crunchy baz 4105
afaik if want end particular order have handle yourself.
Comments
Post a Comment