gpt4 book ai didi

python - 复制与 Pandas 中的多个列模式匹配的列值

转载 作者:行者123 更新时间:2023-11-30 22:28:14 29 4
gpt4 key购买 nike

我碰巧有以下 DataFrame:

import pandas as pd
import numpy as np

df = pd.DataFrame({ 'Prod1': ['10','','10','','',''],
'Prod2': ['','5','5','','','5'],
'Prod3': ['','','','8','8','8'],
'String1': ['','','','','',''],
'String2': ['','','','','',''],
'String3': ['','','','','',''],
'X1': ['x1','x2','x3','x4','x5','x6'],
'X2': ['','','y1','','','y2']
})
print(df)

Prod1 Prod2 Prod3 String1 String2 String3 X1 X2
0 10 x1
1 5 x2
2 10 5 x3 y1
3 8 x4
4 8 x5
5 5 8 x6 y2

这是一个产品与关联字符串的示意图;实际的字符串位于 (X1, X2) 列中,但它们最终应该移动到 (String1, String2 , String3) 根据相应的产品是否有值(value)。

例如:0 行在 Prod1 上有一个值,因此 x1 应移至 String11 行在 Prod2 上有一个值,因此 x2 应移至 String2

在实际数据集中,大多数Prod都有一个String,但是在Prods中存在多个值的行,并且应该填充String列优先考虑左侧。最终结果应如下所示:

  Prod1 Prod2 Prod3 String1 String2 String3 X1 X2
0 10 x1
1 5 x2
2 10 5 x3 y1
3 8 x4
4 8 x5
5 5 8 x6 y1

我正在考虑嵌套的列/行循环,但我仍然对 pandas 不够熟悉,无法找到解决方案。提前非常感谢您的任何建议!

最佳答案

我分解了步骤:

df[['String1', 'String2', 'String3']]=(df[['Prod1', 'Prod2', 'Prod3']]!='')
df1=df[['String1', 'String2', 'String3']].replace({False:np.nan}).stack().to_frame()
df1[0]=df[['X1','X2']].replace({'':np.nan}).stack().values
df[['String1', 'String2', 'String3']]=df1[0].unstack()
df.replace({None:''})


Out[1036]:
Prod1 Prod2 Prod3 String1 String2 String3 X1 X2
0 10 x1 x1
1 5 x2 x2
2 10 5 x3 y1 x3 y1
3 8 x4 x4
4 8 x5 x5
5 5 8 x6 y2 x6 y2

关于python - 复制与 Pandas 中的多个列模式匹配的列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46676830/

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