Select 行基于条件并从向量中设置值

Select rows based on condition and set values from a vector

如果满足列中的条件,我想将整行设置为向量中的值。

import pandas as pd

df = pd.DataFrame([['a', 1, 1], ['a', 1, 1], ['b', 1, 1]], columns=('one', 'two', 'three'))
vector = pd.Series([2,3,4])
print(df)

  one  two  three
0   a    1      1
1   a    1      1
2   b    1      1

我想要的结果是这样的:

df_wanted = pd.DataFrame([['a', 1, 1], ['a', 1, 1], ['b', 4, 4]], columns=('one', 'two', 'three'))
print(df_wanted)

  one  two  three
0   a    1      1
1   a    1      1
2   b    4      4

我试过了,但它给了我错误:

df.loc[df['one']=='b'] = vector[df['one']=='b']
ValueError: Must have equal len keys and value when setting with an iterable

//米

您可以在列表中为集合指定列:

df.loc[df['one']=='b', ['two', 'three']] = vector[df['one']=='b']
print(df)
  one  two  three
0   a    1      1
1   a    1      1
2   b    4      4

或者如果需要更多动态解决方案 - select 所有数字列:

df.loc[df['one']=='b', df.select_dtypes(np.number).columns] = vector[df['one']=='b']

或者只比较一次并赋值给变量:

m = df['one']=='b'
df.loc[m, df.select_dtypes(np.number).columns] = vector[m]