1

my dataframe-:

Unnamed: 0     AsF      demos   Unnamed: 1  Unnamed: 2  Unnamed: 3  Unnamed: 4
1               2        3        3            3           3          3    
2               3        4        6             6          6          6


Expected result-:

               AsF     demos    
1               2        3        3            3           3          3    
2               3        4        6             6          6          6

i tried 
df.rename( columns={'Unnamed: 0':'','Unnamed: 1':''}, inplace=True)


But I can't do that, because number of this kind of columns("unnamed:0") is not fix

I want to do this,because when i convert DF into CSV, it comes with "Unnamed" name that I do not want.

Thanks in Advance

Coder
  • 1,129
  • 10
  • 24
  • 1
    So you want the columns to be nameless? That's not an option... How will pandas know which column to access? – snatchysquid Jun 03 '20 at 08:58
  • @snatchysquid I want to set all "Unnamed: " to " " this – Coder Jun 03 '20 at 09:00
  • `pd.to_csv('file.csv', header=False)` - this writes csv without column header names. [Documentation](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html#pandas-dataframe-to-csv) – Andrej Kesely Jun 03 '20 at 09:00

2 Answers2

2

Fortunately, .rename()'s column param can also get a function, and not just a dict!

you can write a simple lambda to check the prefix of the column name, like this:

df = df.rename(columns=lambda col: '' if col.startswith('Unnamed:') else col)
Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
  • 1
    try and rid your self of the `inplace=True` and your golden [see this](https://stackoverflow.com/a/59242208/9375102) – Umar.H Jun 03 '20 at 09:07
-2

try this:

 df.columns = df.columns[0:2]+[''] * len(df.columns[2:]) 
 df.to_csv('filename.csv', header=False)
Atlas Bravoos
  • 360
  • 2
  • 12
  • Thanks ,but those two columns will be removed!, I don't want to do that – Coder Jun 03 '20 at 09:03
  • with header false columns are not removed what so ever. only header row will not be inserted. is uggest you check this documentation "https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html" – Atlas Bravoos Jun 03 '20 at 09:05
  • I meant to say this!! columns (names)(it will remove all column names) – Coder Jun 03 '20 at 09:17