【问题标题】:How can I transfer df1 to df2 by using dictionary or other method如何使用字典或其他方法将 df1 传输到 df2
【发布时间】:2019-08-25 11:50:24
【问题描述】:

我正在使用 python 3 并且有一个显示为 df1 的 DataFrame,我如何将 df1 转换为 df2?

非常感谢!

【问题讨论】:

  • 嗨,安迪!欢迎来到 StackOverflow!请在完成tour 之后,一定要看看How to create a Minimal, Reproducible Example。然后,编辑添加预期输出的问题。另外,请编辑以文本格式(不是图像)提供数据的问题。

标签: python-3.x dataframe dictionary


【解决方案1】:

首先拆分列名并将它们存储在临时数据框中。

import pandas as pd
temp = pd.DataFrame(df1.T.apply(lambda x: x.index)[0].str.split("_EXP_").tolist(), columns=['name1', 'name2'])

print(temp)

    name1        name2
0      5R      25Delta
1      5R      50Delta
2      5R     -25Delta
3      3R      25Delta
4      3R      50Delta
5      3R     -25Delta

向临时表添加值。

temp['val'] = df1.T[0].values

print(temp)

    name1        name2     val
0      5R      25Delta       1
1      5R      50Delta       2
2      5R     -25Delta       3
3      3R      25Delta       4
4      3R      50Delta       5
5      3R     -25Delta       6

然后使用pivot 函数创建一个reshape 的表。

df2 = temp.pivot(index='name2', columns='name1', values='val')

print(df2)

name1        3R  5R
name2
-25Delta      6   3
25Delta       4   1
50Delta       5   2

如果您的索引和列顺序很重要,请重新排序。

# Reset index manually
df2 = df2.reindex(["25Delta", "50Delta", "-25Delta"]) 

# Reverse the column order
df2 = df2[df2.columns[::-1]] 

print(df2)

name1        5R  3R
name2
25Delta       1   4
50Delta       2   5
-25Delta      3   6

【讨论】:

    猜你喜欢
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 2020-05-02
    相关资源
    最近更新 更多