python - 根据条件将 Pandas DataFrame 列从 String 转换为 Int

标签 python pandas dataframe

我有一个看起来像的数据框

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。我试过了:

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 的整个系列进行比较。一个简单的方法是将 bool 系列转换为 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

bool 比较的输出:

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

关于python - 根据条件将 Pandas DataFrame 列从 String 转换为 Int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31790287/

相关文章:

Python:根据多个条件返回值的 Lambda 函数

python - 更改 pandas 列的日期格式(月-日-年到日-月-年)

python - sns.Facetgrid 未显示正态分布线并忽略空间警告

r - 自定义类继承 `data.frame`及替换方法

python - 需要检查一个数据帧是否是另一个数据帧的子集

Pythonsolve_ivp 与 R lsoda

python - 使用python在二维数组中选择具有特定值的随机索引

python - 如何根据某些列从 pandas 数据框中选择相同的行

python - 每天使用 twisted 重置 redis 键

python - 在数据框中搜索组合以更改单元格值