Search code examples
python-3.xpandaspandas-datareader

Grabbing specific rows and export those to another csv


What i am trying to do here, grabbing specific rows by name. And my csv data table is horizontal. Not vertical, you can see here. Yellow part is headers.

The sample is like below.

---
Row 1 DATA DATA DATA
---
Row 2 YSS  YDD   GGS
---
Row 3 DATA DATA DATA
---
Row 4 DATA DATA DATA
---

Parse row 2, 3, 4 and then export it to another new.csv file. Tricky part is. After exporting the another file. I want to change row 2's data names.

new.csv sample is:

Row 2 YSS  YDD  GGS
---
Row 3 DATA DATA DATA
---
Row 4 DATA DATA DATA
---

So trying to give names to Row 2's data. For example if YSS then make YSS -> Google or if it's YDD then make it Yahoo. Export is a new2.csv again, is like:

Row 2 Google  Yahoo  Facebook
---
Row 3 DATA    DATA   DATA
---
Row 4 DATA    DATA   DATA
---

I start with this but I can't get what want.

import pandas as pd

df = pd.read_csv("datas.csv", index_col=0)
df = df.drop(columns=df.columns[df.iloc[0].isnull()]._data)
df_out = df.loc['利用額(Fee抜き)','クライアント名','媒体'] 

print(df_out)

KeyError: 'the label [クライアント名] is not in the [columns]'


Solution

  • IIUC, you may need something like this:

    Considering the df looks like :

        0       1       2       3
    0   Row 2   YSS     YDD     GGS
    1   Row 3   DATA    DATA    DATA
    2   Row 4   DATA    DATA    DATA
    
    d = {'YSS':'Google','YDD':'Yahoo','GGS':'Facebook'}
    df.T.loc[1:,0] = df.T.loc[1:,0].map(d)
    >>df
    
        0       1       2       3
    0   Row 2   Google  Yahoo   Facebook
    1   Row 3   DATA    DATA    DATA
    2   Row 4   DATA    DATA    DATA
    

    If Row 2 is not a column instead an index just do:

    df.loc['Row 2'] = df.loc['Row 2'].map(d)
    >>df
    
            1       2       3
    0           
    Row 2   Google  Yahoo   Facebook
    Row 3   DATA    DATA    DATA
    Row 4   DATA    DATA    DATA