[英]Data Cleaning with Pandas in Python
I am trying to clean a csv file for data analysis.我正在尝试清理 csv 文件以进行数据分析。 How do I convert TRUE FALSE into 1 and 0?
如何将 TRUE FALSE 转换为 1 和 0?
When I search Google, they suggested df.somecolumn=df.somecolumn.astype(int)
.当我搜索谷歌时,他们建议
df.somecolumn=df.somecolumn.astype(int)
。 However this csv file has 100 columns and not every column is true false(some are categorical, some are numerical).然而,这个 csv 文件有 100 列,并不是每一列都是真假(有些是分类的,有些是数字的)。 How do I do a sweeping code that allows us to convert any column with TRUE FALSE to 1 and 0 without typing 50 lines of
df.somecolumn=df.somecolumn.astype(int)
我如何做一个全面的代码,允许我们将任何具有 TRUE FALSE 的列转换为 1 和 0,而无需键入 50 行
df.somecolumn=df.somecolumn.astype(int)
you can use:您可以使用:
df.select_dtypes(include='bool')=df.select_dtypes(include='bool').astype(int)
A slightly different approach.略有不同的方法。 First, dtypes of a dataframe can be returned using
df.dtypes
, which gives a pandas series that looks like this,首先,可以使用 df.dtypes 返回 dataframe 的
df.dtypes
,这给出了一个看起来像这样的 pandas 系列,
a int64
b bool
c object
dtype: object
Second, we could replace bool
with int type using replace
,其次,我们可以使用
replace
将bool
替换为 int 类型,
df.dtypes.replace('bool', 'int8')
, this gives df.dtypes.replace('bool', 'int8')
,这给出了
a int64
b int8
c object
dtype: object
Finally, pandas seires is essentially a dictionary which can be passed to pd.DataFrame.astype
.最后, pandas seires 本质上是一个字典,可以传递给
pd.DataFrame.astype
。
We could write it as a oneliner,我们可以把它写成一个单行,
df.astype(df.dtypes.replace('bool', 'int8'))
I would do it like this:我会这样做:
df.somecolumn = df.somecolumn.apply(lambda x: 1 if x=="TRUE" else 0)
If you want to iterate through all your columns and check wether they have TRUE/FALSE values, you can do this:如果您想遍历所有列并检查它们是否具有 TRUE/FALSE 值,您可以这样做:
for c in df:
if 'TRUE' in df[c] or 'FALSE' in df[c]:
df[c] = df[c].apply(lambda x: 1 if x=='TRUE' else 0)
Note that this approach is case-sensitive and won't work well if in the column the TRUE/FALSE values are mixed with others.请注意,此方法区分大小写,如果列中的 TRUE/FALSE 值与其他值混合使用,将无法正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.