有没有简单的方法可以将 Pandas 数据框中的是/否列更改为 1/0?
- 2025-03-20 08:48:00
- admin 原创
- 39
问题描述:
我将一个 csv 文件读入 pandas 数据框,并希望将包含二进制答案的列从是/否字符串转换为 1/0 的整数。下面,我展示了其中一个列(“sampleDF”是 pandas 数据框)。
In [13]: sampleDF.housing[0:10]
Out[13]:
0 no
1 no
2 yes
3 no
4 no
5 no
6 no
7 no
8 yes
9 yes
Name: housing, dtype: object
非常感谢您的帮助!
解决方案 1:
方法 1
sample.housing.eq('yes').mul(1)
方法 2
pd.Series(np.where(sample.housing.values == 'yes', 1, 0),
sample.index)
方法 3
sample.housing.map(dict(yes=1, no=0))
方法 4
pd.Series(map(lambda x: dict(yes=1, no=0)[x],
sample.housing.values.tolist()), sample.index)
方法 5
pd.Series(np.searchsorted(['no', 'yes'], sample.housing.values), sample.index)
全部收益
0 0
1 0
2 1
3 0
4 0
5 0
6 0
7 0
8 1
9 1
定时
给定样本
定时
长采样
sample = pd.DataFrame(dict(housing=np.random.choice(('yes', 'no'), size=100000)))
解决方案 2:
尝试一下:
sampleDF['housing'] = sampleDF['housing'].map({'yes': 1, 'no': 0})
解决方案 3:
# produces True/False
sampleDF['housing'] = sampleDF['housing'] == 'yes'
以上代码分别返回 True/False 值,本质上是 1/0。布尔值支持求和函数等。如果您确实需要它是 1/0 值,则可以使用以下命令。
housing_map = {'yes': 1, 'no': 0}
sampleDF['housing'] = sampleDF['housing'].map(housing_map)
解决方案 4:
%timeit
sampleDF['housing'] = sampleDF['housing'].apply(lambda x: 0 if x=='no' else 1)
每循环 1.84 毫秒 ± 56.2 微秒(7 次运行的平均值 ± 标准差,每次 1000 次循环)
对于指定的 df 列,将“是”替换为 1,将“否”替换为 0。
解决方案 5:
使用 sklearn 的 LabelEncoder
from sklearn.preprocessing import LabelEncoder
lb = LabelEncoder()
sampleDF['housing'] = lb.fit_transform(sampleDF['housing'])
来源
解决方案 6:
是的,您可以使用以下代码片段将列的“是/否”值更改为 1/0
sampleDF = sampleDF.replace(to_replace = ['yes','no'],value = ['1','0'])
sampleDF
通过使用第一行,你可以用 1/0 替换值,通过使用第二行,你可以通过打印来查看更改
解决方案 7:
通用方法:
import pandas as pd
string_data = string_data.astype('category')
numbers_data = string_data.cat.codes
参考:
https ://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.astype.html
解决方案 8:
对于数据集名称数据和名为的列Paid
;
data = data.replace({'Paid': {'yes': 1, 'no': 0}})
所有的yes
将变为1
,所有的no
将替换为0
解决方案 9:
您可以明确地将一系列布尔值转换为整数:
sampleDF['housing'] = sampleDF['housing'].eq('yes').astype(int)
解决方案 10:
简单的方法是使用熊猫,如下所示:
housing = pd.get_dummies(sampleDF['housing'],drop_first=True)
之后从主 df 中删除此文件
sampleDF.drop('housing',axis=1,inplace=True)
现在在你的 df 中合并新的
sampleDF= pd.concat([sampleDF,housing ],axis=1)
解决方案 11:
将整个数据框转换为 0 和 1 的一个简单直观的方法可能是:
sampleDF = sampleDF.replace(to_replace = "yes", value = 1)
sampleDF = sampleDF.replace(to_replace = "no", value = 0)
解决方案 12:
sampleDF['housing'] = sampleDF['housing'].map(lambda x: 1 if x == 'yes' else 0)
sampleDF['housing'] = sampleDF['housing'].astype(int)
这会起作用。
解决方案 13:
尝试一下,它会起作用的。
sampleDF.housing.replace(['no', 'yes'], [0,1], inplace = True)
解决方案 14:
使用 pandas.Series.map
sampleDF.map({'yes':1,'no':0})
解决方案 15:
请尝试以下操作:
sampleDF['housing'] = sampleDF['housing'].str.lower().replace({'yes': 1, 'no': 0})
解决方案 16:
我使用了 sklearn 的预处理函数。首先创建一个编码器。
e = preprocessing.LabelEncoder()
然后对于数据中的每个属性或特征,使用标签编码器将其转换为整数值
size = le.fit_transform(list(data["size"]))
color = le.fit_transform(list(data["color"]))
它会转换所有“尺寸”或“颜色”属性的列表,并将其转换为其对应整数值的列表。要将所有这些放入一个列表中,请使用 zip 函数。
它不会采用与 csv 文件相同的格式;它将是所有内容的巨大列表。
data = list(zip(buying, size))
希望我能解释得更清楚一些。
解决方案 17:
您还可以尝试:
sampleDF["housing"] = (sampleDF["housing"]=="Yes")*1
解决方案 18:
这只是一个 bool 到 int。
尝试一下。
sampleDF.housing = (sampleDF.housing == 'yes').astype(int)
解决方案 19:
理解数组
sampleDF['housing'] = [int(v == 'yes') for v in sampleDF['housing']]
扫码咨询,免费领取项目管理大礼包!