python - 如何有效地将数组解码为 pandas 数据框中的列

标签 python pandas dataframe

我有一个函数可以生成一年中每个月的结果。在我的数据框中,我收集不同数据列的这些结果。之后,我有一个包含多个列的数据框,其中数组作为值。现在我想“旋转”这些列,使每个值都在自己的列中。 例如,如果一行在“A”列中包含值 [1,2,3,4,5,6,7,8,9,10,11,12],我想要十二列“A_01”,“A_02'、...、'A_12',每个都包含数组中的一个值。

我当前的代码是这样的:

    # create new columns
    columns_to_add = []
    column_count = len(columns_to_process)

    for _, row in df[columns_to_process].iterrows():
        columns_to_add += [[row[name][offset] if type(row[name]) == list else row[name]
                            for offset in range(array_len) for name in range(column_count)]]

    new_df = pd.DataFrame(columns_to_add,
                          columns=[name+'_'+str(offset+1) for offset in range(array_len)
                                   for name in columns_to_process],
                          index=df.index)  # make dataframe addendum

(注意:有些行没有任何值,因此我必须将条件 if type() == list 放入迭代中)

但是这段代码非常慢。我相信一定有一个更优雅的解决方案。你能告诉我这样的解决方案吗?

最佳答案

IIUC,使用Series.tolistpandas.DataFrame构造函数。

我们将使用DataFrame.rename以及修复您的列名称格式。

# Setup
df = pd.DataFrame({'A': [ [1,2,3,4,5,6,7,8,9,10,11,12] ]})

pd.DataFrame(df['A'].tolist()).rename(columns=lambda x: f'A_{x+1:0>2d}')

[输出]

   A_01  A_02  A_03  A_04  A_05  A_06  A_07  A_08  A_09  A_10  A_11  A_12
0     1     2     3     4     5     6     7     8     9    10    11    12

关于python - 如何有效地将数组解码为 pandas 数据框中的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59084768/

相关文章:

python - APScheduler 随机关闭

python - Pandas to_html float_format

python - 如何在 Pandas 数据框中将两列合并为一列

python-3.x - pandas 数据帧中的跳转点 : the moment when the value in a column gets changed

python - 两个数据帧之间的相关性

python - 如何将嵌套的 json 结构转换为数据框

python - Pandas:将数据帧存储在多个 json 文件中

python - 使用 Mechanize 使用 Python 发送 POST 参数

python - Pandas HDFStore : difference between using the select function and direct access

python - 计算 Dataframe 一个月中下第三个星期五之前的天数