2017-12-13 3 views
0

사용자가 * CSV 파일을 입력하는 스크립트를 작성 중입니다. 이 CSV 파일에는 여러 개의 "필수 열"(이 열이 없으면 오류가 발생 함)과 "기본 열"(이 열을 제공하지 않으면 기본값이 있다고 가정 함)이 있습니다. 나는 후자를 다루는 방법을 혼란 스럽다.팬더 데이터 프레임에 대해 "기본 열"을 사용하는 방법은 무엇입니까?

여기에 구체적인 예입니다 :

import pandas as pd 

df = pd.read_csv("inputfile1.csv") 
print(df) 

    filename   category type 
0 records1.txt  3   A1 
1 records2.txt  4   A1 
2 records7.txt  5   A1 
3 records8.txt  1   C4 

이 파일이 두 개의 필수 열 filenamecategory, 및 디폴트의 열 type. 사용자가 대신 입력 한 경우 :

import pandas as pd 

df = pd.read_csv("inputfile1b.csv") 
print(df) 

    filename   category 
0 records1.txt  3   
1 records2.txt  4   
2 records7.txt  5   
3 records8.txt  1   

나는 type 각 행에 대한 값 A1의 있다고 가정합니다.

어떻게 이러한 기본값을 설정합니까? 한 가지 시도는 열이 있는지 여부를 확인하는 것입니다. 하지 않을 경우, 어떻게 든 특정 행이 값이없는 경우 내가 뭘 이러한 값 그러나

if 'type' not in df.columns: 
    df.type = "A1" 

A1을 만들? 이들은 또한 A1

import pandas as pd 

df = pd.read_csv("inputfile1c.csv") 
print(df) 

    filename   category type 
0 records1.txt  3     ### this is A1 
1 records2.txt  4   A1 
2 records7.txt  5     ### this is A1 
3 records8.txt  1   C4 

답변

1

fillna 당신은 같은

# Create a default dictionary with column names and respective default values 
default_dict = {'col1':1,'col2':2} 

# Now read the input file 
df = pd.read_csv("inputfile1b.csv") 

# After this find list of columns missing in df 
missing_cols = list(set(df_default.columns) - set(df.columns)) 

# Add the missing columns with default values 

for i in missing_cols: 
    df[i] = default_dict[i] 
0

작동합니다 기본값으로 행을 고려되어야한다 누락 된로 간주 할 수 있습니다 값을 변경하려면 다음을 시도하십시오.
df.type.fillna('A1', inplace = True)

-1

을 할 수있는 사전을 사용할 수있다

if 'type' not in df: 
    df['type'] = "A1" 
else: 
    df['type'].fillna('A1', inplace=True) 
관련 문제