我在Python的pandas
数据框中有一个列,其中包含布尔值True
/False
,但是为了进行进一步计算,我需要将它们表示为1
/0
。是否有快速的pandas
/numpy
方法来实现这个目标?
我在Python的pandas
数据框中有一个列,其中包含布尔值True
/False
,但是为了进行进一步计算,我需要将它们表示为1
/0
。是否有快速的pandas
/numpy
方法来实现这个目标?
这是一个基于现有答案的可重现示例:
import pandas as pd
def bool_to_int(s: pd.Series) -> pd.Series:
"""Convert the boolean to binary representation, maintain NaN values."""
return s.replace({True: 1, False: 0})
# generate a random dataframe
df = pd.DataFrame({"a": range(10), "b": range(10, 0, -1)}).assign(
a_bool=lambda df: df["a"] > 5,
b_bool=lambda df: df["b"] % 2 == 0,
)
# select all bool columns (or specify which cols to use)
bool_cols = [c for c, d in df.dtypes.items() if d == "bool"]
# apply the new coding to a new dataframe (or can replace the existing one)
df_new = df.assign(**{c: lambda df: df[c].pipe(bool_to_int) for c in bool_cols})
真%(奇数)= 1 假%(奇数)= 0
import pandas as pd
# create a sample DataFrame with True/False values
df = pd.DataFrame({'A': [True, False, True], 'B': [False, True, False]})
# convert True/False values to 1/0 using view()
df['A'] = df['A'].view('i1')
df['B'] = df['B'].view('i1')
# print the resulting DataFrame
print(df)