根据 pandas 中的条件对数据列进行切片
slicing a datacolumn based on a condition in pandas
我有df,
A B
0 a 1.0
1 b,c 2.0
2
3 c,d NaN
我正在尝试切片 df["A"] when df["B"] is NaN or empty space " "
,我通过 (,) 切片失败 请帮助我实现它,我想要的输出是,
out_df,
A B
0 a 1.0
1 b,c 2.0
2
3 c NaN
我相信你需要用 |
链接的条件,但是为了检查多个空格,最好先将列转换为 string
(因为可能的混合类型 - 数字和字符串),然后 strip
用于将一个或多个空格转换为空字符串:
df = df.loc[df['B'].isnull() | (df['B'].astype(str).str.strip() == ''), 'A']
print (df)
2
3 c,d
Name: A, dtype: object
str.match
的替代解决方案:
df = df.loc[df['B'].isnull() | (df['B'].astype(str).str.match('\s+')), 'A']
编辑:
df['A'] = df['A'].mask(df['B'].isnull() | (df['B'].astype(str).str.strip() == ''),
df['A'].str.split(',').str[0])
print (df)
A B
0 a 1.0
1 b,c 2.0
2
3 c NaN
使用 np.where
即
df['new'] = np.where((pd.isnull(df['B']))|(df['B']==''), df['A'].str.split(',').str[0], df['A'])
或df.where
即
df['A'].where((pd.notnull(df['B']))|(df['B']==''), df['A'].str.split(',').str[0])
A B new
0 a 1 a
1 b,c 2 b,c
2
3 c,d NaN c
我有df,
A B
0 a 1.0
1 b,c 2.0
2
3 c,d NaN
我正在尝试切片 df["A"] when df["B"] is NaN or empty space " "
,我通过 (,) 切片失败 请帮助我实现它,我想要的输出是,
out_df,
A B
0 a 1.0
1 b,c 2.0
2
3 c NaN
我相信你需要用 |
链接的条件,但是为了检查多个空格,最好先将列转换为 string
(因为可能的混合类型 - 数字和字符串),然后 strip
用于将一个或多个空格转换为空字符串:
df = df.loc[df['B'].isnull() | (df['B'].astype(str).str.strip() == ''), 'A']
print (df)
2
3 c,d
Name: A, dtype: object
str.match
的替代解决方案:
df = df.loc[df['B'].isnull() | (df['B'].astype(str).str.match('\s+')), 'A']
编辑:
df['A'] = df['A'].mask(df['B'].isnull() | (df['B'].astype(str).str.strip() == ''),
df['A'].str.split(',').str[0])
print (df)
A B
0 a 1.0
1 b,c 2.0
2
3 c NaN
使用 np.where
即
df['new'] = np.where((pd.isnull(df['B']))|(df['B']==''), df['A'].str.split(',').str[0], df['A'])
或df.where
即
df['A'].where((pd.notnull(df['B']))|(df['B']==''), df['A'].str.split(',').str[0])
A B new 0 a 1 a 1 b,c 2 b,c 2 3 c,d NaN c