如何使用条件填充数据?

2024-04-24 19:57:17 发布

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


Tags: python
3条回答

将groupby和ffill()与bfill()一起使用:

df.groupby('POSTAL_CD').apply(lambda x: x.ffill().bfill())

   Unnamed: 0 POSTAL_CD COUNTRY
0         0.0    33-101      PL
1         1.0    277 32      CZ
2         2.0    72-010      PL
3         3.0    33-101      PL
4         4.0      7700      BE
5         5.0    72-010      PL
6         6.0    33-101      PL
7         7.0     10095      IT
8         8.0    33-101      PL
9         9.0    33-101      PL

如何使用loc索引器as shown here。你知道吗

df = pd.read_csv("sample.csv", sep=",", index_col=0)
df.loc[df["POSTAL_CD"].str.contains("-", na=False), "COUNTRY"] = "PL"

np.where检查用str.contains

df['COUNTRY']=np.where(df['POSTAL_CD'].str.match(r'\d{2}-\d{3}')&df['COUNTRY'].isnull(),'PL',df['COUNTRY'])

相关问题 更多 >