创建一个包含50列的空数据框,其中只有5列被填充



我有一个熊猫数据框架a,它有5列和10万行。我需要创建一个数据框B,它有50列,其中45列为空,另外5列填充数据框a中的数据。

我需要这种格式的原因是因为我想最终转换为具有(,)分隔符且大多数列为空的csv文件。

我的Dataframe A看起来像这样:

<表类> id 为 第一个 在 类型 tbody><<tr>1111约翰尼德普类型12222琥珀听到type2
import pandas as pd
a = pd.DataFrame({"id": [1, 2], "order": [111, 222], "first": ["Johnny", "Amber"], "last": ["Depp", "Heard"], "type": ["type1", "type2"]})
push = ["x", "order", "first", "last"] + list("x" * 7) + ["type"] + list("x" * 4)
cols = [f"x{num}" if value == "x" else value for num, value in enumerate(push)]
b = pd.DataFrame({col: a[col] if col in a.columns.to_list() else None for col in cols})
print(b)

似乎是一个相当随意的问题,但我认为这解决了您的具体要求。您可以随意更改"x" * 7值以反映您的愿望。如果你用import numpy as np,你也可以用np.nan代替None。或者您可以将None替换为""以插入空字符串。你的问题用"空"来表示有点模糊。

输出:

x0  order   first   last    x4    x5    x6    x7    x8    x9   x10   type   x12   x13   x14   x15
0  None    111  Johnny   Depp  None  None  None  None  None  None  None  type1  None  None  None  None
1  None    222   Amber  Heard  None  None  None  None  None  None  None  type2  None  None  None  None

好的,所以我假设数据框B已经有前5列填充了您需要的数据。

你可以通过循环添加任意数量的空白列:

i=4 # However many columns the df started with
while i < 50: # or however many blank columns you want to add
df[f'column_{i}'] = ''
i+=1

最新更新