Подтвердить что ты не робот

кадр данных pandas преобразует столбцы INT64 в boolean

Некоторая колонка в dataframe df, df.column, хранится как тип данных int64.

Все значения равны 1 или 0.

Есть ли способ заменить эти значения булевыми значениями?

4b9b3361

Ответ 1

df['column_name'] = df['column_name'].astype('bool')

Например:

import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.random_integers(0,1,size=5), 
                  columns=['foo'])
print(df)
#    foo
# 0    0
# 1    1
# 2    0
# 3    1
# 4    1

df['foo'] = df['foo'].astype('bool')
print(df)

доходность

     foo
0  False
1   True
2  False
3   True
4   True

Учитывая список column_names, вы можете преобразовать несколько столбцов в bool dtype, используя:

df[column_names] = df[column_names].astype(bool)

Если у вас нет списка имен столбцов, но вы хотите преобразовать, скажем, все числовые столбцы, то вы можете использовать

column_names = df.select_dtypes(include=[np.number]).columns
df[column_names] = df[column_names].astype(bool)

Ответ 2

Ссылка: Переполнение стека unutbu (9 января в 13:25), BrenBarn (18 сентября 2017 г.)

У меня были числовые столбцы, такие как возраст и ID, которые я не хотел преобразовывать в логические. Таким образом, после идентификации числовых столбцов, как показал нам unutbu, я отфильтровал столбцы, которые имели максимум больше 1.

# code as per unutbu
column_names = df.select_dtypes(include=[np.number]).columns 

# re-extracting the columns of numerical type (using awesome np.number1 :)) then getting the max of those and storing them in a temporary variable m.
m=df[df.select_dtypes(include=[np.number]).columns].max().reset_index(name='max')

# I then did a filter like BrenBarn showed in another post to extract the rows which had the max == 1 and stored it in a temporary variable n.
n=m.loc[m['max']==1, 'max']

# I then extracted the indexes of the rows from n and stored them in temporary variable p.
# These indexes are the same as the indexes from my original dataframe 'df'.
p=column_names[n.index]

# I then used the final piece of the code from unutbu calling the indexes of the rows which had the max == 1 as stored in my variable p.
# If I used column_names directly instead of p, all my numerical columns would turn into Booleans.
df[p] = df[p].astype(bool)