数据帧:基于列值指定整数值

2024-04-19 02:04:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的熊猫数据帧。你知道吗

df = pd.DataFrame({'Neighborhood': ['Marble Hill', 'Chelsea', 'Sutton Place'],
                   'Venue Category': ['Hospital', 'Bridge', 'School']})

当我执行它时,我得到下表。你知道吗

 Neighborhood Venue Category
0 Marble Hill Hospital
1 Chelsea Bridge
2 Sutton Place School

现在,我要为每个场馆类别指定数值。你知道吗

Hospital - 5 marks
School - 4 marks
Bridge - 2 marks

所以我试着用这个代码分配标记。我想在一个单独的列中显示标记。你知道吗

def df2(df):

    if (df['Venue Category'] == 'Hospital'):
        return 5
    elif (df['Venue Category'] == 'School'):
        return 4
    elif (df['Venue Category'] != 'Hospital' or df['Venue Category'] != 'School'):
        return np.nan
df['Value'] = df.apply(df2, axis = 1)

一旦执行,它会给我以下警告。我能知道怎么修这个吗?你知道吗

/home/jupyterlab/conda/envs/python/lib/python3.6/site-packages/ipykernel_launcher.py:9: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  if __name__ == '__main__':

Tags: dataframedfreturnplacebridgecategoryschoolmarble
1条回答
网友
1楼 · 发布于 2024-04-19 02:04:06

为所有可能的Venue Category创建字典,然后使用^{},如果返回字典键中不存在的列中的某个值NaN

df = pd.DataFrame({'Neighborhood': ['Marble Hill', 'Chelsea', 'Sutton Place', 'aaa'],
                   'Venue Category': ['Hospital', 'Bridge', 'School', 'a']})

print (df)
   Neighborhood Venue Category
0   Marble Hill       Hospital
1       Chelsea         Bridge
2  Sutton Place         School
3           aaa              a

d = {'Hospital':5, 'School':4, 'Bridge':2}
df['Value'] = df['Venue Category'].map(d)
print (df)
   Neighborhood Venue Category  Value
0   Marble Hill       Hospital    5.0
1       Chelsea         Bridge    2.0
2  Sutton Place         School    4.0
3           aaa              a    NaN

np.select解决是可能的,但在我看来过于复杂:

conditions = [df['Venue Category'] == 'Hospital',
              df['Venue Category'] == 'School',
              df['Venue Category'] == 'Bridge']
choices = [5,4,3]
df['Value'] = np.select(conditions, choices, default=np.nan)

print (df)
   Neighborhood Venue Category  Value
0   Marble Hill       Hospital    5.0
1       Chelsea         Bridge    3.0
2  Sutton Place         School    4.0
3           aaa              a    NaN

相关问题 更多 >