假设我有一些数据帧df
,我想创建一个新的数据帧new_df
,其中n
行与df
中的idx
行相同。与相比,有没有办法在更少的线路中做到这一点
import pandas as pd
df = pd.DataFrame()
new_df = pd.DataFrame()
for i in range(n):
new_df.loc[i] = df.iloc[idx]
感谢
您可以使用repeat
:
N = 5
new_df = df.loc[df.index.repeat(N)]
# or for a particular row idx
new_df = df.loc[df.loc[idx].index.repeat(N)]
或者,对于具有drop=True
:的新索引reset_index
new_df = df.loc[df.index.repeat(N)].reset_index(drop=True)
# or for a particular row idx
new_df = df.loc[df.loc[idx].index.repeat(N)].reset_index(drop=True)
注意如果输入中有多行,并且只想重复一行或几行用df.loc[['idx1', 'idx2', 'idx3']].index.repeat(N)
的df.loc[idx].index.repeat(N)
替换df.index.repeat(N)
示例输入:
df = pd.DataFrame([['A', 'B', 'C']])
输出:
0 1 2
0 A B C
1 A B C
2 A B C
3 A B C
4 A B C
样本:
np.random.seed(100)
df = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (df)
A B C D E
0 8 8 3 7 7
1 0 4 2 5 2
2 2 2 1 0 8
3 4 0 9 6 2
4 4 1 5 3 4
您可以按行idx
创建字典/列表,并调用DataFrame构造函数:
idx = 2
N = 10
df1 = pd.DataFrame(df.loc[idx].to_dict(), index=range(N))
df1 = pd.DataFrame([df.loc[idx].tolist()], index=range(N), columns=df.columns)
print (df1)
A B C D E
0 2 2 1 0 8
1 2 2 1 0 8
2 2 2 1 0 8
3 2 2 1 0 8
4 2 2 1 0 8
5 2 2 1 0 8
6 2 2 1 0 8
7 2 2 1 0 8
8 2 2 1 0 8
9 2 2 1 0 8
使用numpy.repeat
和DataFrame.loc
的另一个解决方案,对于默认索引,使用DataFrame.reset_index
和drop=True
:
idx = 2
N = 10
df1 = df.loc[np.repeat(idx, N)].reset_index(drop=True)
print (df1)
A B C D E
0 2 2 1 0 8
1 2 2 1 0 8
2 2 2 1 0 8
3 2 2 1 0 8
4 2 2 1 0 8
5 2 2 1 0 8
6 2 2 1 0 8
7 2 2 1 0 8
8 2 2 1 0 8
9 2 2 1 0 8
性能比较(与我的数据,在您的真实数据中进行bset测试(:
np.random.seed(100)
df = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (df)
idx = 2
N = 10000
In [260]: %timeit pd.DataFrame([df.loc[idx].tolist()], index=range(N), columns=df.columns)
690 µs ± 44.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [261]: %timeit pd.DataFrame(df.loc[idx].to_dict(), index=range(N))
786 µs ± 106 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [262]: %timeit df.loc[np.repeat(idx, N)].reset_index(drop=True)
796 µs ± 26.3 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
@mozway solution
In [263]: %timeit df.loc[df.index.repeat(N)].reset_index(drop=True)
3.62 ms ± 178 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
@original solution
In [264]: %%timeit
...: nnew_df = pd.DataFrame(columns=df.columns)
...: for i in range(N):
...: new_df.loc[i] = df.iloc[idx]
...:
2.44 s ± 274 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)