如何在列表指定位置追加元素及Python多自变量散点图绘制问题
问题1:如何将一组数字在列表的不同索引位置分别追加到不同的列表中?
可以根据索引规则(比如奇偶、指定索引集合)遍历源列表,把对应元素分配到不同列表,以下是两种常见场景的实现:
场景1:按索引奇偶分配
source_nums = [10, 20, 30, 40, 50, 60] list_even_idx = [] list_odd_idx = [] for idx, num in enumerate(source_nums): if idx % 2 == 0: # 偶数索引元素存入list_even_idx list_even_idx.append(num) else: # 奇数索引元素存入list_odd_idx list_odd_idx.append(num) print(list_even_idx) # 输出: [10, 30, 50] print(list_odd_idx) # 输出: [20, 40, 60]
场景2:按指定索引集合分配
如果要把特定索引位置的元素分到目标列表:
source_nums = [1, 2, 3, 4, 5] list_target = [] list_other = [] # 指定要提取的索引集合 target_indices = {1, 3} for idx, num in enumerate(source_nums): if idx in target_indices: list_target.append(num) else: list_other.append(num) print(list_target) # 输出: [2, 4] print(list_other) # 输出: [1, 3, 5]
问题2:在Python中,如何在单个散点图中可视化多个自变量与单个因变量的关系?
先看你代码的问题:
plt.scatter()仅接受一维数组/Series作为x和y参数,不能直接传入多列DataFrame- 列名
"Bathroom,"多了个逗号,会导致找不到对应列 - 索引语法错误,
df[["Bedroom",...], df["Price"]]应为df[["Bedroom",...]](缺少闭合括号)
以下是两种可行的实现方法:
方法1:用Matplotlib循环绘制
import matplotlib.pyplot as plt import pandas as pd # 示例数据框(替换成你的实际数据) df = pd.DataFrame({ "Bedroom": [2, 3, 3, 4, 2], "Bathroom": [1, 2, 2, 3, 1], "Building_Size": [80, 100, 110, 150, 70], "Plot_of_Land": [200, 250, 280, 350, 180], "Price": [300, 400, 420, 550, 280] }) # 自变量列名(修正后的正确名称) features = ["Bedroom", "Bathroom", "Building_Size", "Plot_of_Land"] # 给每个特征分配不同颜色,方便区分 colors = ["red", "blue", "green", "orange"] plt.figure(figsize=(10, 6)) # 循环每个自变量,绘制散点 for feat, color in zip(features, colors): plt.scatter(df[feat], df["Price"], color=color, label=feat) plt.xlabel("Feature Values") plt.ylabel("Price") plt.title("Multiple Features vs Price") plt.legend() # 显示图例,区分不同自变量 plt.show()
方法2:用Seaborn简化实现
先把数据转成长格式,再用Seaborn一键绘制:
import seaborn as sns import pandas as pd # 转成长格式(melt) df_melt = df.melt( id_vars="Price", value_vars=features, var_name="Feature", value_name="Value" ) plt.figure(figsize=(10, 6)) sns.scatterplot(data=df_melt, x="Value", y="Price", hue="Feature", palette=colors) plt.title("Multiple Features vs Price") plt.show()
内容的提问来源于stack exchange,提问作者Jimoh endurance
相关产品推荐
相关产品推荐

