2017-12-14 8 views
0

을 PT2 결합 :그래서 난 다음 나는 결합하려는 이러한 CSV 파일을대로 해당 값을 추가하는 두 팬더의 dataframes이

file1.csv 
Date,Time,Unique1,Common 
blah,blah,55,92 

file2.csv 
Date,Time,Unique2,Common 
blah,blah,12,25 

내가 어디 팬더 dataframe을 원하는 ...

Date,Time,Unique1,Unique2,Common (order of columns doesn't matter) 
blah,blah,55,12,117 

.. 어디 92 + 25는 117입니다.

다음 코드 샘플을 가진이 게시물과 정확히 같은 제목의 게시물을 발견했습니다 :

each_df = (pd.read_csv(f) for f in all_files) 
full_df = pd.concat(each_df).groupby(level=0).sum() 

날짜 및 시간 열을 전달하지 않는다는 점을 제외하고는 필요한 작업을 수행합니다. 그 이유는 sum()이 그것을 어떻게 처리해야할지 모르기 때문입니다.

내가 대신 좀 ..

Unique1,Unique2,Common 
<values as expected> 

은 날짜 및 시간 열을 통과 제발 도와주세요. 그들은 각 파일에서 정확히 같아야하므로 '날짜'와 '시간'열을 기준으로 데이터를 색인화해도됩니다.

미리 감사드립니다.

+0

여기에 '어쩌구'를 넣으세요. 하지만 당신이 합류하고있는 날짜와 시간 컬럼은 무엇입니까? – MattR

+0

안녕하세요, Matt, 그렇습니다. 색인을 생성 할 항목입니다. – oompaloompa

답변

1

concat 대신 merge을 찾고 있다고 생각합니다.

new_df = df2.merge(df1, on=['Date','Time'], how='inner') 
new_df['Common'] = new_df['Common_x'] + new_df['Common_y'] 
new_df[['Date', 'Time','Unique1', 'Unique2' ,'Common']] 
#output 

    Date Time Unique1 Unique2 Common 
0 blah blah  55  12  117 

당신은이 하나의 라이너 시도 할 수 있습니다 : 두 개 이상의 데이터 프레임에 대한

one_line = df2.merge(df1, on=['Date','Time'], how='inner').\ 
set_index(['Date', 'Time','Unique1', 'Unique2']).sum(axis=1).reset_index().\ 
rename(columns = {0:'Common'}) 

#output 

    Date Time Unique1 Unique2 Common 
0 blah blah  55  12  117 
+0

감사합니다. Matt, 필자는 10 CSV를 반복 할 때마다 하나의 결합 된 CSV를 생성해야합니다.이 개념을 수동으로 확장하는 것만은 알지만 모든 CSV를 선택하는 가장 좋은 방법은 무엇입니까? DF, 그리고 그들 에게이 과정을 수행하십시오. – oompaloompa

+0

불행히도 귀하가 게시 한 질문에 추가 된 내용입니다. 제목은 두 개의 데이터 프레임을 결합합니다. 귀하의 질문을 편집하십시오 - 그러나 그 시점에서 너무 광범위 할 수 있습니다. 루프하는 법을 안다면, 그냥 'new_df' 나'one_line'을 가지고 루프가 필요할 때 루프를 통해 반복 할 수 있습니다. – MattR

0

을,이있을 수 있습니다 더 나은 옵션 각 CSV는 dataframe로 설정되어있는 경우에는 다음을 수행 할 수 있습니다 : 당신은이 기능을 줄이는 방법에 대해 읽을 수 있습니다

import pandas as pd 
from functools import reduce 

# We will be splitting the data into two groups 
all_files1 = (pd.read_csv(f) for f in all_files) 
all_files2 = (pd.read_csv(f) for f in all_files) 

# Merge the data frames together dropping the 'Common' column and set an index 
# Default is an inner join. 
split_drop_common = reduce(lambda df1, df2 : df1.merge(df2, on=['Date','Time']), 
       [df.drop(columns='Common') for df in all_files1]).set_index(['Date','Time']) 
# set up the second group 
stage = pd.concat(all_files2) 

# Drop any of the unique columns and sum the 'Common' column 
keep_columns = ['Date','Time','Common'] 
split_only_common = stage[keep_columns].groupby(['Date','Time']).sum() 


# Join on indices. Default is an inner join. 
# You can specify the join type with kwarg how='join type' 
combine = split_drop_common.join(split_only_common) 
combine 

# Output 

    Date Time Unique1 Unique2 Common 
0 blah blah  55  12  117 

here 작동합니다.

+0

고맙습니다 .. 몇 가지 질문을해도 괜찮 으면 .. in split_drop_common, df1과 df2는 어디에서 시작됩니까? 또한 비 일반적인 열이 모두 '고유'로 시작하는 것은 아니며 문자 그대로 고유 한 이름입니다 ... – oompaloompa

+0

고유 한 이름을 허용하도록 코드를 수정하고 Python이 기능을 어떻게 감소시키는 지에 대한 답변을 SO에게 제공했습니다. –

관련 문제