Haseeb Sultan
Haseeb Sultan

Reputation: 103

Addition of a column into a dataframe

import pandas as pd
import numpy as np
import feather

import glob

path = r'C:/Users/user1/Desktop/Test' # use your path
all_files = glob.glob(path + "/*.csv")

li = []

for i,filename in enumerate (all_files):
    
    df = pd.read_csv(filename, ',' ,index_col=None, header=0).assign(user_iD=filename)
    
    li.append(df)

data = pd.concat(li, axis=0, ignore_index=True)
df = data.copy()

df.to_feather('KT2test.ftr')
data1= pd.read_feather('KT2test.ftr')
data1.tail(50)

The output I'm getting in the user_iD column is C:/Users/user1/Desktop/Test\u9.csv Although I only want user_id as u9 or only 9

How to get this done?

Here is the output image screenshot

Upvotes: 0

Views: 46

Answers (2)

user15729434
user15729434

Reputation:

df = df.assign(user_iD=filename.split("\\u")[-1].split(".")[0])

Upvotes: 0

DragonsCanDance
DragonsCanDance

Reputation: 461

df = pd.read_csv(filename, ',' ,index_col=None, header=0).assign(user_iD=filename.split("\\")[-1].split(".")[0])

Upvotes: 1

Related Questions