0

After stacking a file, the header row is empty i.e. no column names. Whatever I've tried has not yielded any change to that.

Thanks.

P.S. Is it possible to stack select columns from a csv, and not all columns that are not an index?

First line of idx_input.csv is a data row, not a column header. Are any of what I've tried valid? I'm simply trying to stack with column names preserved. What I do in JMP I'd like to do in Pandas.

data_file = pd.read_csv(filename)
idx_input = data_file.set_index(default_stack_group).stack()

default_stack_group = ['X','Y']
cols = default_stack_group + ['Label','Data']

#Option 1 I tried
#idx_input.reset_index().rename(columns{0:cols[0],1:cols[1],2:cols[2],3:cols[3]})

#Option 2 I tried
#idx_input.reset_index()
#idx_input.rename(columns=0:cols[0],1:cols[1],2:cols[2],3:cols[3]},inplace=True)

#Option 3 I tried
#idx_input.columns = cols

idx_input.to_csv('idx_input.csv')

No error message observed (besides a warning)

trial_crunch.py:38: FutureWarning: The signature of Series.to_csv was aligned to that of DataFrame.to_csv, and argument 'header' will change its default val ue from False to True: please pass an explicit value to suppress this warning. idx_input.to_csv('idx_input2.csv')

My first row is already a data column and not a header column. The data is stacked.

  • Welcome to StackOverflow. Please take the time to read this post on [how to provide a great pandas example](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) as well as how to provide a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve) and revise your question accordingly. – anky Aug 07 '19 at 06:44
  • Problem is you forget allign values back... – jezrael Aug 07 '19 at 06:44
  • Use `dx_input = dx_input.reset_index().rename(columns{0:cols[0],1:cols[1],2:cols[2],3:cols[3]})` – jezrael Aug 07 '19 at 06:45
  • Jezrael, you've marked this as duplicate. Could you point me to the original? What I've tried from other places (and suggestions here) on Stack Overflow have not worked. Thanks. – Aniruddh Rangarajan Aug 08 '19 at 17:35

1 Answers1

0

Try using:

idx_input.columns[:4] = cols
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • Here's what I've tried. None of these worked. Note, I have 9 columns. # 1: idx_input = idx_input.reset_index().rename(columns{0:cols[0],1:cols[1],2:cols[2],3:cols[3],4:cols[4],5:cols[5],6:cols[6],7:cols[7],8:cols[8]}) # 2: idx_input.columns[:8] = cols # 3: idx_input.reset_index() #idx_input = idx_input.rename(columns={0:cols[0],1:cols[1],2:cols[2],3:cols[3],4:cols[4],5:cols[5],6:cols[6],7:'Label',8:'Data'},inplace=True) For 1st one, I get "Invalid Syntax" on the line. For 2nd, I get " 'Series' object has no attribute 'columns' ". For 3rd, just a warning but no change to output. – Aniruddh Rangarajan Aug 07 '19 at 23:24