2017-01-16 4 views
0

나는 다음과 같은 것을 완전히 잃어 버렸습니다. 나는 짹짹과 메타 데이터로 가득 찬 테스트 데이터 프레임을 가지고있다. 이제 특정 조건 (예 : 모든 리트 윗 선택)에서 행을 복사하여 새 CSV에 쓰고 싶습니다.파이썬 | 팬더 데이터 프레임의 행 선택

문제는 팬더에서 행을 선택하는 방법을 이해하지 못했지만 설명서를 참조했지만 여전히 퍼즐입니다. .loc과 .ix를 시도했지만 잘못하고 있다고 생각합니다. 그래서 내 생각은 rownumbers를 추가하고 counter와 .ix를 사용하여이 rownumbers에 기초하여 색인을 작성하는 것이 었습니다. 따라서 내 색인은 정수이므로 다음과 같이 작동 할 수 있습니다.

selectRow = file_df.ix[counter,:] 

제외 전체 행을 선택하는 방법에 대한 도움말? 아마 뭔가 쉽게 빠져있을거야.

총 코드 : # Script는 트윗을 선택하고 전체 행을 새 파일로 인쇄하여 리트 윗을 선택합니다.

import pandas as pd 
import string 

print("Loading file & initializing variables.") 

# load file 
file_df = pd.read_csv("Desktop/tweetsamples.csv", delimiter=";") 

#declare stuff we need to use 
output_df = pd.DataFrame() 
rowToCopy = pd.Series() 
selectRow = pd.Series() 
withoutPuncSeries = pd.Series() 
counter = 0 
retweet = False 
username = "" 

print("Working.. Please be patient.") 

# define for loop which checks if there is a retweet in the tweet 

content = file_df["header"] 

splitContent = [content.str.split()] #initialize list 
for wordsLists in splitContent: 
    counter = counter + 1 
    for wordsList in wordsLists: 
     if wordsList[0] == "RT": 
      retweet = True 
      username = wordsList[1] 
      withoutPunctuation = "" #initialize/reset placeholder string 
      for char in username: #we want to get rid of potential interpunction errors behind the username, so we loop through the string 
       if char != "@": #we don't want to have the @ 
        if char == "_" or char not in string.punctuation: #only desired characters ('_' is a valid char in an username) 
         withoutPunctuation = withoutPunctuation + char.lower() #add to placeholder string 
      print "Found retweet from:", withoutPunctuation 
      withoutPuncSeries = [withoutPunctuation] 
      selectRow = file_df.ix[counter,:] 

    rowToCopy = [selectRow, withoutPuncSeries] 
    output_df = output_df.append(rowToCopy) 
    rowToCopy = pd.Series() #reset 
    withoutPuncSeries = pd.Series() 

output_df.to_csv("Desktop/retweet test.csv", sep=";") 

print("Done.") 
+1

[MCVE]를 제공 할 수 있습니까? – IanS

+0

전체 행을 어떻게 선택 하시겠습니까? –

답변

0

당신은 df.iloc[row] 단일 행 또는 df.iloc[startrow:endrow]와 범위를 선택할 수 있습니다. 귀하의 경우에는 문제를 일으킬 수있는 여분의 쉼표가 있습니다.

+0

위의 두 가지를 사용하여 단일/다중 행을 선택할 수 있습니다. –

0

조건에 따라 행을 선택하려면이 방법이 효과적입니다.

def my_function(header): 
    if header[0]=='RT': #or whatever your condition is 
     return True 
    else: 
     return False 


df_new = df[df['header'].apply(my_function)] 
df_new.to_csv('../only_rt.csv') 
0

당신이 찾고있는 것은 부울 마스킹이라고 생각합니다. 문제는 데이터 구조가 매우 명확하지 않다는 것입니다. pandas 문자열 등 contains, startswith에서 작동하는 많은 기능을 갖고, 등등

retweet_df = file_df[file_df['header'].str.contains('RT') & ....] 

부울 마스크, |를 논리 연산자 & (및)을 통해 결합 된 복수의 문장을 포함 (또는) ~ (생략) 할