基于条件将 Pandas DataFrame 列从 String 转换为 Int [英] Convert Pandas DataFrame Column From String to Int Based on Conditional
本文介绍了基于条件将 Pandas DataFrame 列从 String 转换为 Int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像的数据框
I have a dataframe that looks like
df
viz a1_count a1_mean a1_std
n 3 2 0.816497
y 0 NaN NaN
n 2 51 50.000000
我想根据条件将viz"列转换为 0 和 1.我试过了:
I want to convert the "viz" column to 0 and 1, based on a conditional. I've tried:
df['viz'] = 0 if df['viz'] == "n" else 1
但我明白了:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
推荐答案
您正在尝试将标量与引发您看到的 ValueError
的整个系列进行比较.一个简单的方法是将布尔系列转换为 int
:
You're trying to compare a scalar with the entire series which raise the ValueError
you saw. A simple method would be to cast the boolean series to int
:
In [84]:
df['viz'] = (df['viz'] !='n').astype(int)
df
Out[84]:
viz a1_count a1_mean a1_std
0 0 3 2 0.816497
1 1 0 NaN NaN
2 0 2 51 50.000000
你也可以使用np.where
:
In [86]:
df['viz'] = np.where(df['viz'] == 'n', 0, 1)
df
Out[86]:
viz a1_count a1_mean a1_std
0 0 3 2 0.816497
1 1 0 NaN NaN
2 0 2 51 50.000000
布尔比较的输出:
In [89]:
df['viz'] !='n'
Out[89]:
0 False
1 True
2 False
Name: viz, dtype: bool
然后转换为 int
:
In [90]:
(df['viz'] !='n').astype(int)
Out[90]:
0 0
1 1
2 0
Name: viz, dtype: int32
这篇关于基于条件将 Pandas DataFrame 列从 String 转换为 Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文