gpt4 book ai didi

python - 将 numpy 数组存储在 pandas 数据框的多个单元格中(Python)

转载 作者:太空宇宙 更新时间:2023-11-04 00:51:29 27 4
gpt4 key购买 nike

我是新来的。我有一个像这样的 Pandas 数据框:

                    078401115X            0790747324            0790750708

A10ODC971MDHV8 0 0 [(354, 1), (393, 1)]
A16CZRQL23NOIW 0 [(124, 1), (697, 1)] 0
A19ZXK9HHVRV1X 0 0 0

我有列为零的索引(第一行):

['078401115X',
'0790747324']

现在,我正在尝试在 pandas 数据框的那些位置存储 numpy 零数组,无论如何都可以直接执行此操作而无需“for 循环”我设法使用标量值,但我不能这样做使用 numpy 数组。

非常感谢您的帮助。

最佳答案

使用.locDataFrame 维度匹配的多行分配

这是一个完整的解决方案,使用零索引的 .loc 并克服了尺寸/长度错误

error: 'cannot set using a list-like indexer with a different length than the value'

为了匹配维度,在分配给零索引而不是分配原始数组时,以您想要/需要的形状创建零数组的 DataFrame

import numpy as np
import pandas as pd
from cStringIO import StringIO

# Create example DataFrame
df_text = '''
078401115X| 0
0790747324| 0
0790750708|[(354, 1), (393, 1), (447, 1), (642, 1), (886,1)]
0800103688| 0
5556167281|[(41, 1), (86, 1), (341, 1), (362, 1), (419, 10)]
6300157423| 0
6300266850| 0
6301699599| 0
6301723465| 0
'''
df = pd.read_table(StringIO(df_text), sep='|', index_col=0, header=None, skipinitialspace=True)

print 'Original DataFrame:'
print df
print

# Find indexes with zero data in first column
zero_indexes = df[df[1] == '0'].index

print 'Zero Indexes:'
print zero_indexes.tolist()
print

# Assign numpy zero array to indexes
df.loc[zero_indexes] = pd.DataFrame([[np.zeros(4)]], index=zero_indexes, columns=[1])

print 'New DataFrame:'
print df

Original DataFrame:
1
0
078401115X 0
0790747324 0
0790750708 [(354, 1), (393, 1), (447, 1), (642, 1), (886,1)]
0800103688 0
5556167281 [(41, 1), (86, 1), (341, 1), (362, 1), (419, 10)]
6300157423 0
6300266850 0
6301699599 0
6301723465 0

Zero Indexes:
['078401115X', '0790747324', '0800103688', '6300157423', '6300266850', '6301699599', '6301723465']

New DataFrame:
1
0
078401115X [0.0, 0.0, 0.0, 0.0]
0790747324 [0.0, 0.0, 0.0, 0.0]
0790750708 [(354, 1), (393, 1), (447, 1), (642, 1), (886,1)]
0800103688 [0.0, 0.0, 0.0, 0.0]
5556167281 [(41, 1), (86, 1), (341, 1), (362, 1), (419, 10)]
6300157423 [0.0, 0.0, 0.0, 0.0]
6300266850 [0.0, 0.0, 0.0, 0.0]
6301699599 [0.0, 0.0, 0.0, 0.0]
6301723465 [0.0, 0.0, 0.0, 0.0]

关于python - 将 numpy 数组存储在 pandas 数据框的多个单元格中(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36938331/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com