如何解决将数据框从循环连接成一个大数据框
我有一个原始数据框,我想在其中覆盖一个循环中的几列。 最后,我想将所有数据帧(在循环中生成)堆叠到一个大数据帧中(该数据帧包含原始数据帧的x倍,并在此进行更改。)dfs的堆叠似乎对我不起作用(并且A列与i的乘积(与i的乘积确实起作用)
通过“ ID”列,我可以跟踪大数据框中的所有不同数据帧,因为在查看ID时,它们显然是在一起的。
尝试的代码:
import pandas as pd
df_or = pd.DataFrame({"Case": [1,2,3,4,5,6],"A": [3,8,1],"B": [10,12,24,57,84]})
print(df_or)
total = []
for i in range(0,2):
df = df_or
df.loc[:,'A'] = df_or.loc[:,'A'].mul(i) #.add(i) works fine
df.loc[:,'ID'] = df.loc[:,'Case'] + i*100000
print(df)
total.append(df)
total = pd.concat(total)
total = total.sort_values('ID')
total.reset_index(inplace=True,drop=True)
print(total)
所需结果:
Case A B ID
0 1 0 10 1
1 2 0 12 2
2 3 0 24 3
3 4 0 8 4
4 5 0 57 5
5 6 0 84 6
6 1 3 10 100001
7 2 5 12 100002
8 3 2 24 100003
9 4 8 8 100004
10 5 4 57 100005
11 6 1 84 100006
相反,我得到了:
Case A B ID
0 1 0 10 100001
1 1 0 10 100001
2 2 0 12 100002
3 2 0 12 100002
4 3 0 24 100003
5 3 0 24 100003
6 4 0 8 100004
7 4 0 8 100004
8 5 0 57 100005
9 5 0 57 100005
10 6 0 84 100006
11 6 0 84 100006
解决方法
您可以尝试以下方法:
df_or['id'] = [i for i in range(1,len(df_or['Case'])+1)]
df1 = df_or.copy()
df_or['id'] = ['10000'+str(i) for i in range(1,len(df_or['Case'])+1)]
df = pd.concat([df1,df_or])
print(df)
Case A B id
0 1 3 10 1
1 2 5 12 2
2 3 2 24 3
3 4 8 8 4
4 5 4 57 5
5 6 1 84 6
0 1 3 10 100001
1 2 5 12 100002
2 3 2 24 100003
3 4 8 8 100004
4 5 4 57 100005
5 6 1 84 100006
要修复代码,您需要使用df = df_or.copy()
:
total = []
for i in range(0,2):
df = df_or.copy()
df.loc[:,'A'] = df_or.loc[:,'A'].mul(i) #.add(i) works fine
df.loc[:,'ID'] = df.loc[:,'Case'] + i*100000
print(df)
total.append(df)
total = pd.concat(total)
total = total.sort_values('ID')
total.reset_index(inplace=True,drop=True)
print(total)
Case A B ID
0 1 0 10 1
1 2 0 12 2
2 3 0 24 3
3 4 0 8 4
4 5 0 57 5
5 6 0 84 6
6 1 3 10 100001
7 2 5 12 100002
8 3 2 24 100003
9 4 8 8 100004
10 5 4 57 100005
11 6 1 84 100006
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。