我正在尝试更新满足某些条件的数据框的某些列(只有某些行会满足条件)。
我正在使用 apply with loc。我的函数返回一个熊猫系列。
问题是列是用 NaN 更新的。
简化我的问题,我们可以考虑以下数据框 df_test:
col1 col2 col3 col4
0 A 1 1 2
1 B 2 1 2
2 A 3 1 2
3 B 4 1 2
我现在想在col1=A时更新col3和col4。为此,我将使用 apply 方法
df_test.loc[df_test['col1']=='A', ['col3', 'col4']] = df_test[df_test['col1']=='A'].apply(lambda row: pd.Series([10,20]), axis=1)
这样做我得到:
col1 col2 col3 col4
0 A 1 NaN NaN
1 B 2 1.0 2.0
2 A 3 NaN NaN
3 B 4 1.0 2.0
如果不是 pd.Series([10, 20]) 我使用 np.array([10, 20]) 或 [10, 20] 我得到以下错误
ValueError: shape mismatch: value array of shape (2,2) could not be broadcast to indexing result of shape (2,)
我需要返回什么才能获得
col1 col2 col3 col4
0 A 1 10 20
1 B 2 1 2
2 A 3 10 20
3 B 4 1 2
谢谢!
您可以通过在 df.apply 的 pd.Series 构造函数中应用正确的索引来解决此问题,如下所示:
df.loc[df['col1'] == 'A', ['col3', 'col4']] = df.loc[df['col1'] == 'A'].apply(lambda x: pd.Series([10,20], index=['col3', 'col4']), axis=1)
注意,我正在将 pd.Series 索引与数据框中的预期列标题进行匹配。 Pandas 执行大多数操作时都会考虑索引对齐。
输出:
col1 col2 col3 col4
0 A 1 10 20
1 B 2 1 2
2 A 3 10 20
3 B 4 1 2