用numpy数组替换pandas数据帧的行

时间:2022-07-26 21:15:52

I have a pandas dataframe, for example:

我有一个pandas数据帧,例如:

import sys
if sys.version_info[0] < 3: 
    from StringIO import StringIO
else:
    from io import StringIO

import pandas as pd

TESTDATA = StringIO("""col1;col2;col3
    (1,2);(3,4);(5,6)
    (7,8);(9,10);(11,12)
    (13,14);(15,16);(17,18)
    (19,20);(21,22);(23,24)
    """)

df = pd.read_csv(TESTDATA, sep=";")

dataframe looks like this:

dataframe看起来像这样:

          col1     col2     col3
0        (1,2)    (3,4)    (5,6)
1        (7,8)   (9,10)  (11,12)
2      (13,14)  (15,16)  (17,18)
3      (19,20)  (21,22)  (23,24)

Now, let's say there's 2 rows 0 and 2 that I wish to replace with a numpy array of zeros such as:

现在,让我们说有2行0和2我希望用numpy数组替换,例如:

np.zeros((1,3,2))
"""array([[[ 0.,  0.],
        [ 0.,  0.],
        [ 0.,  0.]]])"""

So the final result is that for the rows 0 and 2, I have tuples (0,0), (0,0), and (0,0). Could someone propose an approach?

所以最后的结果是对于行0和2,我有元组(0,0),(0,0)和(0,0)。有人可以提出方法吗?

1 个解决方案

#1


1  

This would work:

这可行:

arr = np.zeros((1, 3, 2))
row = [tuple(t) for t in arr[0]]
df.loc[0] = row
df.loc[2] = row

#1


1  

This would work:

这可行:

arr = np.zeros((1, 3, 2))
row = [tuple(t) for t in arr[0]]
df.loc[0] = row
df.loc[2] = row