【问题标题】:Append a list to the first row and column of a pandas dataframe将列表附加到熊猫数据框的第一行和第一列
【发布时间】:2019-10-27 16:53:30
【问题描述】:

我有一个 4300 x 4300 的 pandas 数据框(行和列),并且想在第一行和第一列中添加一个列表。我不知道该怎么做,没有用零完全填充数据框......

旧的 4300 x 4300 数据帧示例(摘录):

要添加的列表示例: ["轴","输出","组","复数","记录"]

新的 A x A 数据框示例:

【问题讨论】:

  • 你能添加一些 5x5 df 和预期输出的示例数据吗?

标签: python-3.x pandas dataframe append


【解决方案1】:

如果列表中的值在索引和列中不存在,则使用DataFrame.reindexIndex.appendIndex.union

L = ["axis","output","group","plurality","record"]
#if order is important
df = df.reindex(index=df.index.append(pd.Index(L)), columns= df.columns.append(pd.Index(L)))

#if index, columns values should be sorted
df = df.reindex(index=df.index.union(L), columns= df.columns.union(L))

如果索引中存在可能的值,列和顺序很重要:

L1 = [x for x in L if x not in df.index]
L2 = [x for x in L if x not in df.columns]

df = df.reindex(index=df.index.append(pd.Index(L1)), columns= df.columns.append(pd.Index(L2)))

【讨论】:

    猜你喜欢
    • 2021-12-02
    • 2019-10-22
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多