2017-11-25 5 views
1

空の配列があります。私はCol1とCol2の値に基づいて追加しようとしました。いずれかの列にゼロより大きい数値が存在する場合は、対応する値に基づいて配列を追加します。例えばPython Pandas真実あいまいなシリーズの値

Col1 Col2 
1   2 
2   3 
0   0 
4   2 

出力は次のようになります。

Col1 Col2 Col3 
1  2  [1,2,2] 
2  3  [1,1,2,2,2] 
0  0  [] 
4  2  [1,1,1,1,2,2] 

コードこれまで戻り 'シリーズの真理値があいまいです。'私は他のトピックのcontextのこのエラーに精通していますが、これを私と調整することはできません。

df = pd.read_csv('rawdata.csv') 

x_array =[] 

for x in df['emails_opened'], df['emails_clicked']: 
    if (x > 0 & pd.notnull(x) & x != '' & x in df['emails_opened']): 
     x_array == np.append(x_array, x * [2]) 
    elif (x > 0 & pd.notnull(x) & x != '' & x in df['emails_clicked']): 
     x_array == np.append(x_array, x * [3]) 
    else: 0 
print x_array 

ご協力いただきありがとうございます。

+0

私はDFでのxに対して 'この構文を考えていない[ 'emails_opened']、DFは[ 'emails_clicked']: は'有効です。 –

答えて

0

私はあなたが必要だと思う:

#replace to 0 by conditions 
m1 = (df['Col2'] > 0) & (df['Col2'].notnull()) & (df['Col2'].astype(str) != '') 
m2 = (df['Col1'] > 0) & (df['Col1'].notnull()) & (df['Col1'].astype(str) != '') 

col1 = df['Col1'].where(m1, 0) 
col2 = df['Col2'].where(m2, 0) 

#repeat array by filtered values, last create list and for no values add empty list 
a = pd.Series(np.repeat([1] * len(col1), col1), 
       index = np.repeat(col1.index, col1)) 

a = a.groupby(level=0).apply(list).reindex(df.index, fill_value=[]) 

b = pd.Series(np.repeat([2] * len(col2), col2), 
       index = np.repeat(col2.index, col2)) 

b = b.groupby(level=0).apply(list).reindex(df.index, fill_value=[]) 


df['Col3'] = a + b 
print (df) 
    Col1 Col2    Col3 
0  1  2   [1, 2, 2] 
1  2  3  [1, 1, 2, 2, 2] 
2  0  0     [] 
3  4  2 [1, 1, 1, 1, 2, 2] 
+0

Jezraelありがとうございます。私はエラーが発生しました」上記の「安全」のルールに従ってdtype( 'float64')からdtype( 'int64')に配列データをキャストできません。それはcol2にはいくつかの行の値がないという事実に関係しているように見えますが、これは!= ''が考慮すると思っています。 – user3479107

+0

あなたのパンダのバージョンは何ですか?最後は '0.21.0'です。多分それは助けます。また、どの行のコードがエラーを返しますか? – jezrael

+0

私は0.21.0です。ギャップは、どのリストにも空白がある場合のようです。空白を0に置き換えるSQLスクリプトを修正し、うまくいきます。お手伝いありがとう! – user3479107

関連する問題