Код: Выделить всё
import polars as pl
df = pl.DataFrame({
'Codes_1': ['302E513', '301E513', '302E512'],
'Codes_2': ['303E513', '306E510', '302E512']}).lazy()
conditions = ['302E513', '306E510']
column_names = ['Codes_1', 'Codes_2']
#create new column
df = df.with_columns(
pl.when(pl.any_horizontal(
pl.col(column_names).str.starts_with(conditions[0]),
pl.col(column_names).str.starts_with(conditions[1])))
.then(1.0)
.otherwise(0.0)
.alias('Column_name')
)
Код: Выделить всё
import polars as pl
df = pl.DataFrame({
'Codes_1': ['302E513', '301E513', '302E512'],
'Codes_2': ['303E513', '306E510', '302E512']}).lazy()
conditions = ['302E513', '306E510', '5164E23', '302E514']
column_names = ['Codes_1', 'Codes_2']
#create new column
df = df.with_columns(
pl.when(pl.any_horizontal(
#Tedious part
pl.col(column_names).str.starts_with(conditions[0]),
pl.col(column_names).str.starts_with(conditions[1]),
pl.col(column_names).str.starts_with(conditions[2]),
pl.col(column_names).str.starts_with(conditions[3])
))
.then(1.0)
.otherwise(0.0)
.alias('Column_name')
)
Код: Выделить всё
import pandas as pd
df = pd.DataFrame({
'Codes_1': ['302E513', '301E513', '302E512'],
'Codes_2': ['303E513', '306E510', '302E512']})
conditions = ['302E513', '306E510']
column_names = ['Codes_1', 'Codes_2']
#loop to create new column
mask = False
for code in conditions:
mask |= df[column_names].eq(code).any(axis=1)
df['Column_name'] = 0.0
df.loc[mask, 'Column_name'] = 1.0
print(df['Column_name'])
Подробнее здесь: https://stackoverflow.com/questions/792 ... aking-a-ne
Мобильная версия