gpt4 book ai didi

python - Pandas 根据多列计算逻辑或

转载 作者:行者123 更新时间:2023-11-28 21:48:54 25 4
gpt4 key购买 nike

这是我正在处理的DataFrame:

{'Recipe@123': ['AAA', nan, nan],
'Recipe@234': [nan, 'BBB', nan],
'Recipe@456': [nan, nan, 'CCC'],
'Operation@123':[1,nan,nan],
'Operation@234':[nan,2,nan],
'Operation@456':[nan,nan, 3]
}

我正在尝试创建一个 Recipe 列,该列将不包含基于行值的 NaN 配方。例如,第一行值将是 AAA,第二行 - BBB 等。DF 中还有其他列,但应考虑 Recipe 列只提到了 3 个。

最佳答案

一个简单的解决方案是:

df = pd.DataFrame({'Recipe@123': ['AAA', np.nan, np.nan], 'Recipe@234': [np.nan, 'BBB', np.nan], 'Recipe@456': [np.nan, np.nan, 'CCC'], 'other_col': [1, 2, 3]})

Recipe@123 Recipe@234 Recipe@456 other_col
0 AAA NaN NaN 1
1 NaN BBB NaN 2
2 NaN NaN CCC 3

只需遍历 并使用 .dropna 去除缺失值,您可以将其写入新的 DataFrame 列像这样:

for i, data in df.iterrows():
df.loc[i, 'Recipe'] = data[['Recipe@123', 'Recipe@234', 'Recipe@456']].dropna().values[0]

Recipe@123 Recipe@234 Recipe@456 other_col Recipe
0 AAA NaN NaN 1 AAA
1 NaN BBB NaN 2 BBB
2 NaN NaN CCC 3 CCC

关于python - Pandas 根据多列计算逻辑或,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34467795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com