Pandas Data Manipulation Column Join, Column Swap, Column Rename

Introduction

It's a story that seems to be everywhere, but I'll forget it soon, so make a note

Sample data

data1.csv


ID,data1
1,data1-1
2,data1-2
3,data1-3

data2.csv


ID,data2
1,data2-1
2,data2-2
3,data2-3

Inner join

import pandas as pd

#Read
df1 = pd.read_csv("sample/data1.csv", index_col=0)
df2 = pd.read_csv("sample/data2.csv", index_col=0)

#Join columns
df = pd.concat([df1, df2], axis=1)
print(df)

result

      data1    data2
ID
1   data1-1  data2-1
2   data1-2  data2-2
3   data1-3  data2-3

Swap columns

df = df.loc[:, ['data2', 'data1']]
print(df)

result

      data2    data1
ID
1   data2-1  data1-1
2   data2-2  data1-2
3   data2-3  data1-3

Rename column

df = df.rename(columns={'data1':'d1', 'data2':'d2'})
print(df)

result

         d2       d1
ID
1   data2-1  data1-1
2   data2-2  data1-2
3   data2-3  data1-3

Recommended Posts

Pandas Data Manipulation Column Join, Column Swap, Column Rename
Data manipulation with Pandas!
Read pandas data
PySpark data manipulation
Data visualization with pandas
Shuffle data with pandas