python数据帧-根据列值复制行
我想根据2列值复制数据框“this”的行,并将它们保存为名为“newThis”的新数据框: 我想要一个连接行的大数组,但我得到的却是这样的混乱:python数据帧-根据列值复制行,python,python-3.x,pandas,numpy,dataframe,Python,Python 3.x,Pandas,Numpy,Dataframe,我想根据2列值复制数据框“this”的行,并将它们保存为名为“newThis”的新数据框: 我想要一个连接行的大数组,但我得到的却是这样的混乱: [array([[1, 5, 2], [1, 5, 2], [1, 5, 2], [1, 5, 2], [1, 5, 2]], dtype=int64), array([[1, 5, 2], [1, 5, 2]], dtype=int64), array([[2, 0, 3
[array([[1, 5, 2],
[1, 5, 2],
[1, 5, 2],
[1, 5, 2],
[1, 5, 2]], dtype=int64), array([[1, 5, 2],
[1, 5, 2]], dtype=int64), array([[2, 0, 3]], dtype=int64), array([[2, 0, 3],
[2, 0, 3],
[2, 0, 3]], dtype=int64), array([[0, 4, 2],
[0, 4, 2],
[0, 4, 2],
[0, 4, 2]], dtype=int64), array([[0, 4, 2],
[0, 4, 2]], dtype=int64)]
谢谢看起来你把np.array和列表相乘搞混了 记住:
[np.int32(1)] * 2 == [np.int32(1), np.int32(1)]
但是:
您可能需要更改以下内容:
np.array([this.iloc[i,:]] * int(this.iloc[i, 1]))
为此:
np.array([this.iloc[i,:]]) * int(this.iloc[i, 1])
IIUC:
资料来源:
In [213]: this
Out[213]:
a b c
1 1 5 2
2 2 0 3
3 0 4 2
解决方案:
In [211]: newThis = pd.DataFrame(np.repeat(this.values,
this['b'].replace(0,1).tolist(),
axis=0),
columns=this.columns)
In [212]: newThis
Out[212]:
a b c
0 1 5 2
1 1 5 2
2 1 5 2
3 1 5 2
4 1 5 2
5 2 0 3
6 0 4 2
7 0 4 2
8 0 4 2
9 0 4 2
请发布您想要的数据集谢谢,虽然这不是我要找的。我想创建一个更长的数据帧,其中每行根据第二列和第三列中的值重复n次。哇,这太棒了,谢谢。原来我原来的大数据集中有一些NaN,我得到了这个:“不能将浮点NaN转换为整数”有什么想法吗?@Sharonio,请发布一个小的可复制数据集(带有NaN的)和你想要的数据集。。。
In [213]: this
Out[213]:
a b c
1 1 5 2
2 2 0 3
3 0 4 2
In [211]: newThis = pd.DataFrame(np.repeat(this.values,
this['b'].replace(0,1).tolist(),
axis=0),
columns=this.columns)
In [212]: newThis
Out[212]:
a b c
0 1 5 2
1 1 5 2
2 1 5 2
3 1 5 2
4 1 5 2
5 2 0 3
6 0 4 2
7 0 4 2
8 0 4 2
9 0 4 2