我一直在研究熊猫数据帧。陷入某种逻辑。有人能帮上忙吗:
这是我的输入数据框:
**df4**
Data1 Description Associated Data
F104 TO F5334
F104 TO F105
F105 TO F1212
F105 TO F5332
F105 IS F104
F5332 IS F105
F5334 IS F104
F1000 IS F1212
F1015 IS F1242
F1015B IS F1242B
F1015B IS F1242
F1212 TO F1000
F1212 TO F1242B
F1212 IS F105
F1242 TO F1015
F1242 TO F1015B
F1242B TO F1015B
F1242B IS F1212
这里有3列: 数据1(键)、描述(用作条件)、关联数据(值)
预期产出:
F104 F5334
F104 F105 F1212
F104 F105 F5332
F104 F105 F1212 F1000
F104 F105 F1212 F1242B
...............
我的代码:
df6 = pd.DataFrame(columns=["Is_Upgrade"])
df4 = df.copy()
for i in range(len(df4)):
print(i)
bas_part = df4.loc[i]["Data1"]
type_part = df4.loc[i]["Description"]
#associate = df4.loc[i]["Associated Data"]
if((str(type_part) == "TO") == True):
df6.loc[i,"Data1"]= str(bas_part)
df6.loc[i,"Upgrade_use"] = df4.loc[i]["Associated Data"]
elif((str(type_part) == "IS") == True):
#if(df6.loc[i]["Upgrade"] == ""):
df6.loc[df6["Data1"]== str(bas_part),"Is_Upgrade"] = df4.loc[i]["Associated Data"]
取得的结果:
F104 F105 F1212
F104 F105 F5332
F105 F1212 F1000
F105 F1212 F1242B
nan F104 F5334
nan F104 F105
F1212 F1242B F1015B
nan F1242 F1015
nan F1242 F1015B
详细说明:
如果描述列值为“TO”,则将关联数据添加到实际数据的右侧
迭代1:
F104, F5334
迭代2:因为我们有条件再次创建具有相同值的新行
F104 F5334
F104 F105
迭代3:因为我们有条件再次创建具有相同值的新行
F104 F5334
F104 F105 F1212
迭代4:因为我们有条件再次创建具有相同值的新行
F104 F5334
F104 F105 F1212
F104 F105 F5332
迭代5:由于我们有条件“是”,现在检查data1左边的值是否与associate相同如果“是”通过,否则添加新值将现有数据移动到新列
F104 F5334
F104 F105 F1212
F104 F105 F5332
迭代7:由于我们有条件“是”,现在检查data1左边的值是否与associate相同如果“是”通过,否则添加新值将现有数据移动到新列
F104 F5334
F104 F105 F1212
F104 F105 F5332
等等
有人能帮忙吗
方法是创建一个函数,用于检查数据帧中的索引值:
现在创建一个for循环:
创建数据框后,我们必须将数据拆分为多列:
输出:
相关问题 更多 >
编程相关推荐