import pandas as pd
import numpy as np
df = pd.DataFrame([
['Quality Engineer','Financial Services'],
['Progammer',np.nan],
['Quality Engineer',np.nan],
['Progammer',"IT"],
['General manager',np.nan]],
columns=['job_title','job_industry'])
with pd.option_context('mode.use_inf_as_null', True):
df = df.sort_values('job_industry', ascending=False, na_position='last')
df["job_industry"].loc[(df['job_title'] == "General manager") & (df['job_industry'].isnull())] = "Manufacturing"
df['job_industry'] = df.groupby('job_title')['job_industry'].fillna(method="ffill")
df['job_industry'].isnull(),这将验证job_industry 列是否为空。
下面的代码会按照job_industry列的null值降序排序,因为如果nan值出现在前面,nan的初始值不会被替换。
with pd.option_context('mode.use_inf_as_null', True):
df = df.sort_values('job_industry', ascending=False, na_position='last')
如果你更喜欢排序而不是输出,你可以试试,df.sort_index()
O/P
+----+------------------+-------------------------------------------------------+
| | job_title | job_industry |
|----+------------------+-------------------------------------------------------|
| 0 | Quality Engineer | Financial Services |
| 1 | Progammer | IT |
| 2 | Quality Engineer | Financial Services |
| 3 | Progammer | IT |
| 4 | General manager | Manufacturing |
+----+------------------+-------------------------------------------------------+