0

I have over 100 csv files, all contain a table with the same indexes and indentical length. I am able to concat them into a single dataframe and save as csv.

print(df)

         a   b   c   d
0    1   5   1   7   7
1    2   3   1   7   7
2    3   2   2   8   7
3    1   6   1   7   6

I want to add a name to the now blank 'initial index' but every solution I find doesn't work... I've tried:

df.rename(columns={'': 'initial'}, inplace=True)
df1 = df.rename(columns={'': 'initial'})
df1 = df.set_index('initial')
df1 = df.rename_axis("initial")

Header printout as is:

print([*df])
[' a b c d']

I am using Python 3.7.3

Edit

Thanks for the feedback. Both Joe Ferndz and icecity96 solutions work. They didn't initially only because .csv file columns were seperated with spaces not comma's, therefore the DataFrame has seen only one column. Problem gone away after adding delim_whitespace=True

pd.read_csv(file, delim_whitespace=True)

Output before:

print(*df)
[' a b c d']

Output after:

print([*df])
['a', 'b', 'c', 'd']
4
  • 1
    That doesn't seem like the output you'd get from print([*df]), unless somehow you have a single column with the label ' a b c d' and everything happened to pretty print perfectly. What is df.index? Commented Aug 28, 2020 at 5:45
  • How many columns do you have in your original dataframe. I think 5 or is it 1? Commented Aug 28, 2020 at 6:53
  • can you do print (list(df)) and tell me what it shows? Does it print ['','a','b','c','d'] ? Commented Aug 28, 2020 at 6:55
  • After finding my mistake all works as intended Commented Aug 29, 2020 at 23:56

2 Answers 2

1

Try:

df.rename({df.columns[0]: 'initial'}, axis='columns', inplace=True)

Output:

>>> print([*df])
['', 'a', 'b']
>>> df.rename({df.columns[0]: 'initial'}, axis='columns', inplace=True)
>>> print([*df])
['initial', 'a', 'b']
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to rename the columns, can't you just do something as simple as this please?

import pandas as pd

df = pd.DataFrame({'' :[1,2,3,4],
                   'A':['A','B','C','D'],
                   'Z':[True, False, False, True]})
print(df)

df.columns = ['New','A','B']

print(df)

Here the first column got renamed as 'New' and also renamed column Z as B

Output is:

Before:

      A      Z
0  1  A   True
1  2  B  False
2  3  C  False
3  4  D   True

After:

   New  A      B
0    1  A   True
1    2  B  False
2    3  C  False
3    4  D   True

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.