簡體   English   中英

如果列名在列中的一個表中並且列名的數據在列中的不同表中,如何創建表

[英]how to create a table if column names are in one table in a column and data for the column names are in different table in a columns

我有兩個 csv 文件,一個有數據的列名,這些列名的數據在該表的一列內的另一個 csv 中。 這是那些 csv 文件的結構

ID unique_ref 錢_花費
1 abcd123 120
2 bcde234 145
3 cdef345 450
4 defg456 412
5 abcd123 127
6 bcde234 148
7 cdef345 489
8 defg456 415
ID 領域
abcd123 蘋果
bcde234 橘子
cdef345 葡萄
defg456 西瓜

現在我想要的是創建另一個 CSV,它將根據 unique_ref 將這些字段作為列並將 money_spent 作為數據。 我無法指定要旋轉或轉置的列名,因為在真實數據中有很多字段。 我可以使用 SQL 或/和 Python

您可以迭代第二個表的id ,用相同的unique_ref屏蔽所有行並unique_ref創建一個列表列表。

the_list = [
    [the_row["fields"], data_1[data_1["unique_ref"] == the_row["id"]]["money_spent"].to_numpy().tolist()]
    for index, the_row in data_2.iterrows()
]

現在你有一個列表:

[['abcd123', [120, 127]], ['bcde234', [145, 148]], ['cdef345', [450, 489]], ['defg456', [412, 415]]]

使用它,您可以創建一個新的數據框:

請注意,您需要對數據進行轉置:

the_df = pd.DataFrame(
    list(map(list, zip(*[i[1] for i in the_list]))),
    columns=[i[0] for i in the_list]
)

數據框:

   apple  orange  grape  watermelon
0    120     145    450         412
1    127     148    489         415

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM