根据条件声明将列添加到pandas df

时间:2020-04-16 22:07:05

标签: pandas dataframe

我有一个名为lin_reg_df的df,有两列Surface_Elevation_mAHDAdopted_SS_WL。 df拥有88个地下水井的测量值,每个井都有一个特定的井名。 lin_reg_dfwell name索引。
我想在df中添加另一列,称为Aquifer_Type,并指定孔是deep还是shallow。 所有deep井的井名称保存在名为deep_wells的列表中,浅井则保存在shallow_wells中 我想循环浏览孔名称(df的索引),如果孔名称列在 我想在deep_wells列中放置一个deep的列表,称为Aquifer_Type。如果列出了 在名为shallow_wells的列表中,我想在shallow列中放置一个Aquifer_Type
我尝试在循环中使用isin,但无法正常工作。 有什么建议吗?

2 个答案:

答案 0 :(得分:0)

我尝试使用以下代码从您的信息中创建一个最小示例:

well_name = ['a','b','c','d','e','f','g']
deep_wells = ['a','c','g']
shallow_wells = ['b','d','e','f']

lin_reg_df = pd.DataFrame({'Surface_Elevation_mAHD ': [1,2,3,4,5,6,7],
                           'Adopted_SS_WL': [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]})
lin_reg_df.index = well_names

所以我的DataFrame最初看起来像这样:

    Surface_Elevation_mAHD  Adopted_SS_WL
a   1                       0.1
b   2                       0.2
c   3                       0.3
d   4                       0.4
e   5                       0.5
f   6                       0.6
g   7                       0.7

然后我只需要使用以下代码片段即可完成工作:

for well in well_name:
    if well in deep_wells:
        lin_reg_df.loc[well, 'Aquifier_Type'] = 'deep'
    elif well in shallow_wells:
        lin_reg_df.loc[well, 'Aquifier_Type'] = 'shallow'

输出将是:

    Surface_Elevation_mAHD  Adopted_SS_WL   Aquifier_Type
a   1                       0.1             deep
b   2                       0.2             shallow
c   3                       0.3             deep
d   4                       0.4             shallow
e   5                       0.5             shallow
f   6                       0.6             shallow
g   7                       0.7             deep

答案 1 :(得分:0)

始终提供数据以更快地获得帮助

数据

#ifndef DEBUG
#define SINLINE static inline __attribute__((always_inline))
#else
#define SINLINE 
#endif

列表

SINLINE void myfunc()
{
   /* ... */
}

另一种方法是将DEBUG用于

df=pd.DataFrame({'Surface_Elevation_mAHD':[3,4,6,7.8,9,2,5],'Adopted_SS_WL':[1,2,3,4,5,6,7],'well name':['WQ','RT','KL','SZ','TR','YH','YP']})
df

如果您的名字是索引。请在应用np.wehere之前将其重置。您可以通过deep_wells=['WQ','RT','YH','YP'] shallow_wells=['KL','SZ','TR']