[Pandas] 여러개의 컬럼 하나로 합치기

2020. 7. 22. 21:34분석 Python/Pandas Tip

728x90

여러개의 변수들을 하나로 합치는 것에 대한 심플 버전은 다음과 같이 apply(axis=1)을 방향으로 합칠 수 있음.

cols = ['sex', 'day', 'smoker']
tip['combined'] = tip[cols].apply(lambda row: '_'.join(row.values.astype(str)), axis=1)

 

복합적으로 다양한 것을 적용해본 결과는 다음과 같음

tip = sns.load_dataset("tips")

def make_original(x) :
    xs = x.dropna()
    xs_np = xs.values
    first = '-'.join(xs_np.astype(str)[:-3])
    original = first + "@" + str(xs_np[-2]) + "_" + str(int(xs_np[-1]))
    return original

cols = ['sex', 'day', 'smoker',"time","size"]
tip.insert(0, 'No', tip[cols].apply(lambda row: make_original(row) , axis=1)) 
tip.head()

 

 

https://stackoverflow.com/questions/39291499/how-to-concatenate-multiple-column-values-into-a-single-column-in-panda-datafram

 

How to concatenate multiple column values into a single column in Panda dataframe

This question is same to this posted earlier. I want to concatenate three columns instead of concatenating two columns: Here is the combining two columns: df = DataFrame({'foo':['a','b','c'], 'ba...

stackoverflow.com

 

728x90