我的.loc具有多个条件,可以继续运行...帮助我降落飞机

时间:2019-03-02 14:51:16

标签: pandas

当我尝试运行下面的代码时,它一直在运行。明显吗?

df.loc[(df['Target_Group'] == 'x') & (df['Period'].dt.year == df['Year_Performed'].dt.year), ['Target_P']] = df.loc[(df['Target_Group'] == 'x') & (df['Period'].dt.year == df['Year_Performed'].dt.year), ['y']]

2 个答案:

答案 0 :(得分:1)

indexcond=(df['Target_Group'] == 'x') & (df['Period'].dt.year == df['Year_Performed'].dt.year) df.loc[cond, 'Target_P'] = df.y 敏感的,因此您无需重复分配条件

df=pd.DataFrame({'cond':[1,2],'v1':[-110,-11],'v2':[9999,999999]})
df.loc[df.cond==1,'v1']=df.v2
df
Out[200]: 
   cond    v1      v2
0     1  9999    9999
1     2   -11  999999

更多信息,例如

df.loc[cond, 'Target_P'] = df.loc[cond,'y'].values

如果索引包含重复

<LinearLayout
android:id="@+id/lnrFinish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_green"
android:orientation="horizontal"
android:clickable="true">

<TextView
    android:id="@+id/txtInto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="12dp"
    android:layout_marginTop="2dp"
    android:layout_marginRight="12dp"
    android:layout_marginBottom="8dp"
    android:gravity="center"
    android:text="End"
    android:textColor="#fff"
    android:textSize="11sp"
    android:clickable="true" />
</LinearLayout>

答案 1 :(得分:1)

我认为您需要为变量分配条件并进行重用:

m = (df['Target_Group'] == 'x') & (df['Period'].dt.year == df['Year_Performed'].dt.year)
df.loc[m, 'Target_P'] = df.loc[m, 'y']

要提高性能,可以使用numpy.where

df['Target_P'] = np.where(m, df['y'], df['Target_P'])