gpt4 book ai didi

python - 在python中连接两个尺寸不等的数据帧

转载 作者:太空宇宙 更新时间:2023-11-03 20:03:42 24 4
gpt4 key购买 nike

我有两个不相等行的数据框。我想将一个数据帧的前 20 行连接到另一个数据帧的前 5 行,并递归执行此操作,直到两个文件的末尾。

示例数据:

df1
col1 col2
1 0.1
2 0.2
3 0.3
4 0.4
5 0.5
6 0.6
20 0.10
21 0.01
22 0.01
23 0.01
24 0.01
40 0.01
100 0.90
df2
col1 col2
1 0.1
2 0.2
3 0.3
4 0.4
5 0.5
6 0.6
7 0.7
8 0.8
9 0.9
10 0.4

输出

col1    col2
1 0.1
2 0.2
3 0.3
4 0.4
5 0.5
6 0.6
20 0.10
1 0.1
2 0.2
3 0.3
4 0.4
5 0.5
20 0.10
21 0.01
22 0.01
23 0.01
24 0.01
40 0.01
6 0.6
7 0.7
8 0.8
9 0.9
10 0.4

谢谢

最佳答案

想法是通过整数除法来更改两个 DataFrame 中的索引,//, concat一起,按 DataFrame.sort_index 排序最后通过 reset_index 创建默认索引:

N1 = 20
N2 = 5

#if not default RangeIndex in both
df1 = df1.reset_index(drop=True)
df2 = df2.reset_index(drop=True)

df1.index //= N1
df2.index //= N2

df = pd.concat([df1, df2]).sort_index(kind='mergesort').reset_index(drop=True)

示例:

df1 = pd.DataFrame({'a':range(20)})
df2 = pd.DataFrame({'a':range(100, 110)})
#print (df1)
#print (df2)

N1 = 5
N2 = 3

df1.index //= N1
df2.index //= N2

df = pd.concat([df1, df2]).sort_index(kind='mergesort').reset_index(drop=True)
<小时/>
print (df)
a
0 0
1 1
2 2
3 3
4 4
5 100
6 101
7 102
8 5
9 6
10 7
11 8
12 9
13 103
14 104
15 105
16 10
17 11
18 12
19 13
20 14
21 106
22 107
23 108
24 15
25 16
26 17
27 18
28 19
29 109

关于python - 在python中连接两个尺寸不等的数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59088086/

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