2017-06-12 8 views
1

Excelシートにデータがあります。私は範囲の1つの列の値をチェックし、その値がその範囲(5000-15000)にある場合、別の列に値を挿入したい(CorrectまたはFlag)。パンダデータフレームに値を挿入

私は3つの列を持っています:都市、賃貸、ステータス。

私は追加と挿入の方法を試しましたが、うまくいかなかった。 どうすればよいですか?ここ

は私のコードである:

インデックス、行のdf.iterrowsに():

if row['city']=='mumbai': 

    if 5000<= row['rent']<=15000: 

     pd.DataFrame.append({'Status': 'Correct'}) 

はこのエラーを示します。

TypeError例外:追加の(1つの)必要な位置引数が欠落します: 'その他'

データを行単位で列に挿入するにはどのような手順を実行する必要がありますか?

答えて

1

私はあなたがbetweencityと比較することにより作成されたboolean型マスクでnumpy.whereを使用することができると思う:

mask = (df['city']=='mumbai') & df['rent'].between(5000,15000) 
df['status'] = np.where(mask, 'Correct', 'Uncorrect') 

はサンプル:loc

df = pd.DataFrame({'city':['mumbai','mumbai','mumbai', 'a'], 
        'rent':[1000,6000,10000,10000]}) 
mask = (df['city']=='mumbai') & df['rent'].between(5000,15000) 
df['status'] = np.where(mask, 'Correct', 'Flag') 
print (df) 
    city rent status 
0 mumbai 1000  Flag 
1 mumbai 6000 Correct 
2 mumbai 10000 Correct 
3  a 10000  Flag 

別の解決策:については

mask = (df['city']=='mumbai') & df['rent'].between(5000,15000) 
df['status'] = 'Flag' 
df.loc[mask, 'status'] = 'Correct' 
print (df) 
    city rent status 
0 mumbai 1000  Flag 
1 mumbai 6000 Correct 
2 mumbai 10000 Correct 
3  a 10000  Flag 

exへの書き込みCELの使用to_excelindex=Falseを追加するインデックス列を削除する必要がある場合:

df.to_excel('file.xlsx', index=False) 

EDIT:

複数maskのためには、使用可能性である:

df = pd.DataFrame({'city':['Mumbai','Mumbai','Delhi', 'Delhi', 'Bangalore', 'Bangalore'], 
        'rent':[1000,6000,10000,1000,4000,5000]}) 
print (df) 
     city rent 
0  Mumbai 1000 
1  Mumbai 6000 
2  Delhi 10000 
3  Delhi 1000 
4 Bangalore 4000 
5 Bangalore 5000 

m1 = (df['city']=='Mumbai') & df['rent'].between(5000,15000) 
m2 = (df['city']=='Delhi') & df['rent'].between(1000,5000) 
m3 = (df['city']=='Bangalore') & df['rent'].between(3000,5000) 

m = m1 | m2 | m3 
print (m) 
0 False 
1  True 
2 False 
3  True 
4  True 
5  True 
dtype: bool 

from functools import reduce 
mList = [m1,m2,m3] 
m = reduce(lambda x,y: x | y, mList) 
print (m) 
0 False 
1  True 
2 False 
3  True 
4  True 
5  True 
dtype: bool 

print (df[m]) 
     city rent 
1  Mumbai 6000 
3  Delhi 1000 
4 Bangalore 4000 
5 Bangalore 5000 
+0

それは正しい結果を示しているが、それは私のExcelシートにデータを書きません –

+0

編集された答えを確認してください。 – jezrael

+0

以前のシートのデータを削除します。これは、ステータスの1つの列のみを挿入します。この場合助けてください –