【问题标题】:How to transform a DataFrame into a dictionary taking just the mapped values?如何将 DataFrame 转换为仅采用映射值的字典?
【发布时间】:2019-10-13 07:54:07
【问题描述】:

我需要在对象的 DataFrame 中重置一些值

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'x': [[0] * 6, ['']],
    'y': [[0, np.nan, 0, 1, 0, 1], [4, 3, 5]],
    'z': [[5, 5, 5, 4, 4, 4], [65, 324, 45.345]]
})

def test(ar):
    if ar == ['']:
        return False
    else:
        return True

df.applymap(test)

applymap 返回这个:

我只需要将带有True 的列和单元格放入如下结构:

d = {
    'x': [(0, [''])],
    'y': [(0, ['']), (1, ['']),]
    'z': [(0, ['']), (1, ['']),]
}

实现这一目标的最快方法是什么?必须有一个简单的方法来解决它。

【问题讨论】:

  • 你问的是如何获取单元格的列索引?

标签: python python-3.x pandas dataframe mapping


【解决方案1】:

可能有一种更聪明的方法可以做到这一点,但这可以完成工作:

>>> df = pd.DataFrame({'x': [True, False], 'y': [True, True], 'z': [True, True]})
>>> df
       x     y     z
0   True  True  True
1  False  True  True

>>> d = {}

>>> for column in df.columns: 
...:     d[column] = [] 
...:     for index, value in enumerate(column): 
...:         if value == True: 
...:             d[column].append((index, [''])) 
...:
>>> d
{'x': [(0, [''])], 'y': [(0, ['']), (1, [''])], 'z': [(0, ['']), (1, [''])]}

提问者改进的算法

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'x': [[0] * 6, ['']],
    'y': [[0, np.nan, 0, 1, 0, 1], [4, 3, 5]],
    'q': [[''], ['']],
    'z': [[5, 5, 5, 4, 4, 4], [65, 324, 45.345]]
})

def test(ar):
    if ar == ['']:
        return False
    else:
        return True

new_df = df.applymap(test)
d = {}
for column in new_df.columns: 
    s = new_df[column][new_df[column] == True]
    if s.size >= 1:
        d[column] = []
        for index, value in enumerate(s): 
            if value == True: 
                d[column].append((index, [''])) 
d

【讨论】:

  • 我已经解决并改进了您算法中的一些错误。但无论如何,我将使用@Quang Hoang 的算法mabe,因为它需要的时间少了几纳秒。我赞成您的回答,因为它有用,谢谢
【解决方案2】:

我不确定这有多有效,但你可以试试:

new_df = df.applymap(test).stack()

# replace True with the empty string
new_df = new_df[new_df].replace({True:''}).reset_index(level=0)

# get the tuples
s = new_df.apply(lambda x: tuple(x), axis=1)

# group the tuples by (original) column names and return dict
d = s.groupby(s.index).apply(lambda x: x.tolist()).to_dict()

输出:

{'x': [(0, '')], 'y': [(0, ''), (1, '')], 'z': [(0, ''), (1, '')]}

由提问者优化算法。如果我直接在applymap 中返回正确的对象,则不需要替换步骤

df = pd.DataFrame({
    'x': [[0] * 6, ['']],
    'y': [[0, np.nan, 0, 1, 0, 1], [4, 3, 5]],
    'q': [[''], ['']],
    'z': [[5, 5, 5, 4, 4, 4], [65, 324, 45.345]]
})
new_df = df.applymap(lambda x: None if x == [''] else [''])
new_df = new_df.stack().reset_index(level=0)
s = new_df.apply(lambda x: tuple(x), axis=1)
d = s.groupby(s.index).apply(lambda x: x.tolist()).to_dict()
d

【讨论】:

    猜你喜欢
    • 2019-05-14
    • 2016-09-02
    • 2017-03-10
    • 2018-11-17
    • 2019-02-06
    • 2014-09-12
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多