【问题标题】:Python: Generate dictionary from pandas dataframe with rows as keys and columns as valuesPython:从熊猫数据框中生成字典,其中行作为键,列作为值
【发布时间】:2018-11-25 16:51:55
【问题描述】:

我有一个如下所示的数据框:

     Curricula Course1 Course2 Course3 ... CourseN
0       q1      c1        c2     NaN        NaN
1       q2      c14       c21    c1         Nan
2       q3      c2        c14    NaN        Nan
...
M       qm      c7        c9     c21

每个课程的课程数量不同。

我需要的是这个数据框中的字典,如下所示:

{'q1': 'c1', 'q1': 'c2', 'q2': 'c14', 'q2': 'c21', 'q2: 'c1' ... }

行名是我的键,对于每一行,字典中都填满了给出的所有 'Curricula': 'Course' 信息,不包括 'NaN' 值。

到目前为止,我尝试将索引设置为“课程”列,转置数据帧并使用 to_dict('records') 方法,但这导致以下输出:

在:

df.set_index('Curricula')
df_transposed = df.transpose()
Dic = df_transposed.to_dict('records')

出来:

[{0: 'q1', 1: 'q2', 2: 'q3', ... }, {0: 'c1', 1: 'c14', 2: 'c2' ...} ... {0: NaN, 1: 'c1', 2: 'Nan']

因此,这里将列整数值用作键,而不是我想要的“课程”列值,此外,不排除 NaN 值。

有人知道如何解决这个问题吗?

最好的问候, 一月

【问题讨论】:

  • 你的字典里怎么会有重复的键?这是不可能的

标签: python pandas dataframe dictionary


【解决方案1】:

设置

df = pd.DataFrame({'Curricula': {0: 'q1', 1: 'q2', 2: 'q3'},
 'Course1': {0: 'c1', 1: 'c14', 2: 'c2'},
 'Course2': {0: 'c2', 1: 'c21', 2: 'c14'},
 'Course3': {0: np.nan, 1: 'c1', 2: np.nan}})

print(df)

  Curricula Course1 Course2 Course3
0        q1      c1      c2     NaN
1        q2     c14     c21      c1
2        q3      c2     c14     NaN

字典中不能有重复的键,但是您可以使用 agg 以及 set_indexstack 为每个唯一键创建一个列表:

df.set_index('Curricula').stack().groupby(level=0).agg(list).to_dict()

{'q1': ['c1', 'c2'], 'q2': ['c14', 'c21', 'c1'], 'q3': ['c2', 'c14']}   

【讨论】:

  • Total newbie = 完全忘记了重复键... xD 我需要一些时间来弄清楚如何解决我的重复键问题。非常感谢您的回答@user3483203!我会继续处理你的答案:)
  • @JanB 还有,我应该提到,在您的代码中,当您调用set_index 时,它不会做任何事情,因为默认情况下set_index 不存在。您可以拨打df.set_index('foo', inplace=True),但您的结果将丢失。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
相关资源
最近更新 更多