【问题标题】: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如果列名在列中的一个表中并且列名的数据在列中的不同表中,如何创建表
【发布时间】:2021-12-23 21:12:54
【问题描述】:

我有两个 csv 文件,其中一个具有数据的列名,这些列名的数据位于该表列内的另一个 csv 中。这是那些csv文件的结构

id unique_ref money_spent
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 fields
abcd123 apple
bcde234 orange
cdef345 grape
defg456 watermelon

现在我想要创建另一个 CSV,它将这些字段作为列,money_spent 作为数据,根据 unique_ref。我无法指定要透视或转置的列名,因为在真实数据中有很多字段。 我可以使用 SQL 或/和 Python

【问题讨论】:

  • 我已经删除了冲突的标签。请只标记您真正使用的RDBMS。
  • 查看 Pandas 文档,这是一个非常有用且功能强大的库,可将数据帧作为 csv 数据文件进行管理。
  • 如果你有 2 个 CSV 文件并且你想要一个 CSV 文件,为什么你需要关于 SQL 或数据库的任何信息作为这个问题的一部分

标签: python sql python-3.x


【解决方案1】:

您可以遍历第二个表的id,用相同的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

【讨论】:

  • 我使用了这个并且很有帮助,但是在最后一部分中,在数据框中进行转换时,它只给了我 1 行。如何获取所有行?
  • 我不知道为什么会这样。这适用于给定的表格。
猜你喜欢
  • 2018-09-05
  • 1970-01-01
  • 1970-01-01
  • 2022-11-15
  • 2012-11-29
  • 1970-01-01
  • 1970-01-01
  • 2018-06-30
  • 1970-01-01
相关资源
最近更新 更多