我有一個熊貓資料框 A,它有 5 列和幾十萬行。我需要創建一個資料框 B,它有 50 列,其中 45 列為空,另外 5 列填充了我在資料框 A 中的資料。
我需要這種格式的原因是因為我想最終轉換為帶有 (,) 分隔符的 csv 檔案,并且大多數列為空。
我的資料框 A 如下所示:
| ID | 命令 | 第一的 | 最后的 | 型別 |
|---|---|---|---|---|
| 1 | 111 | 約翰尼 | 德普 | 型別1 |
| 2 | 222 | 琥珀色 | 聽到 | 型別2 |
我的 Dataframe B 應該看起來像這樣,最后有更多的空列:
| X | 命令 | 第一的 | 最后的 | X | X | X | X | X | X | X | 型別 | X | X | X | X |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 空的 | 111 | 約翰尼 | 德普 | 空的 | 空的 | 空的 | 空的 | 空的 | 空的 | 空的 | 型別1 | 空的 | 空的 | 空的 | 空的 |
| 空的 | 222 | 琥珀色 | 聽到 | 空的 | 空的 | 空的 | 空的 | 空的 | 空的 | 空的 | 型別2 | 空的 | 空的 | 空的 | 空的 |
如您所見,我需要為列指定列的位置type。這是因為我最終想使用
to_csv(delimiter=',')最終看起來像這樣的函式轉換為 CSV:
,111,Johnny,Depp,,,,,,,,,type1,,,,,
,222,Amber,Heard,,,,,,,,,type2,,,,,
uj5u.com熱心網友回復:
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值以反映您的意愿。如果你也可以替換None為. 或者您可以替換為插入空字串。說“空”,您的問題有點含糊。np.nanimport numpy as npNone""
輸出:
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
uj5u.com熱心網友回復:
好的,所以我假設資料框 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/484936.html
上一篇:我只能使用[0:1]之類的切片視窗對我的pandas資料框進行切片以獲取特定行,為什么[0會引發KeyError?
