如何将一个数据帧转换成一个只接受映射值的字典?

2024-09-30 02:15:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要重置对象数据帧中的一些值

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返回:

df

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

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

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


Tags: 数据对象方法testimporttruepandasdf
2条回答

也许有一种更聪明的方法可以做到这一点,但这可以完成任务:

>>> 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, [''])]}

asker算法的改进

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

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

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

相关问题 更多 >

    热门问题