根据条件选择行并从向量中设置值

时间:2019-10-07 11:14:51

标签: python pandas dataframe indexing selection

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

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

// m。

1 个答案:

答案 0 :(得分:1)

您可以在列表中指定要设置的列:

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

或者,如果需要更多动态解决方案,请选择所有数字列:

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]