python - Dataframe 从列表中添加多列,并创建每个列名

标签 python dataframe

有一个字典列表d,其中x是一个嵌入列表,例如

d = [{"name":"Python", "x":[0,1,2,3,4,5]},  # x has 300 elements
     {"name":"C++", "x":[0,1,0,3,4,4]},
     {"name":"Java","x":[0,4,5,6,1]}]

我想将 d 转换为 Dataframe,并为 x 中的每个元素自动添加列,添加的列名有一个前缀 "abc”,例如,

df.columns = ["name", "abc0", "abc1", ..., "abc300"]

我正在寻找一种有效的方法,因为 d 有很多字典。当我手动添加列时,Python 说

PerformanceWarning: DataFrame is highly fragmented.  This is usually the result of calling `frame.insert` many times, which has poor performance.  Consider joining all columns at once using pd.concat(axis=1) instead.  To get a de-fragmented frame, use `newframe = frame.copy()`

最佳答案

你在找这样的东西吗:

d = [{"name":"Python", "x":[0,1,2,3,4,5]},  # x has 300 elements
     {"name":"C++", "x":[0,1,0,3,4,4]},
     {"name":"Java","x":[0,4,5,6,1]}]

df = pd.DataFrame(
    {
        "name": record["name"],
        **{f"abc{i}": n for i, n in enumerate(record["x"])}
    }
    for record in d
)

您的样本结果:

     name  abc0  abc1  abc2  abc3  abc4  abc5
0  Python     0     1     2     3     4   5.0
1     C++     0     1     0     3     4   4.0
2    Java     0     4     5     6     1   NaN

关于python - Dataframe 从列表中添加多列,并创建每个列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70285992/

相关文章:

python - 将多列求和为两列输出/数据帧

scala - 如何重新整理Spark数据框中的行?

python - 如果 Pandas 数据框中的特定列中存在空值,则删除行

python - 如何分析 `paster serve` 的启动时间?

python - 霍夫圆中标量变量错误的无效索引

python - 在 Python 中, 'x or False' 和 'False and x 有什么意义?

python - 无法在 Google Cloud 中训练我的 Tensorflow 检测器模型

python - Pandas - 比较多个数据帧的值,并保留多数值

python - 将列表中的字符串插入数据框公式以在 Pandas 中循环计算

python - 如何从 sphinx 编译中获取警告列表