为什么我的数据框列发生了变化?

时间:2018-03-06 13:27:24

标签: python pandas

我的代码

import pandas as pd
import numpy as np

series = pd.read_csv('o1.csv', header=0)

s1 = series
s2 = series

s1['userID'] = series['userID'] + 5
s1['adID'] = series['adID'] + 3
s2['userID'] = s1['userID'] + 5
s2['adID'] = series['adID'] + 4

r1=series.append(s1)
r2=r1.append(s2)

print(r2)

我出错了,现在列完全一样了。 输出

    userID gender  adID  rating
0       11      m   107      50
1       11      m   108     100
2       11      m   109       0
3       12      f   107      50
4       12      f   108     100
5       13      m   109      62
6       13      m   114      28
7       13      m   108      36
8       12      f   109      74
9       12      f   114     100
10      14      m   108      62
11      14      m   109      28
12      15      f   116      50
13      15      f   117     100
0       11      m   107      50
1       11      m   108     100
2       11      m   109       0

我不想要更改系列列。 为什么会这样? 怎么改变这个? 我需要使用iloc吗?

1 个答案:

答案 0 :(得分:2)

如果需要新对象DataFrame IIUC需要copy

s1 = series.copy()
s2 = series.copy()

<强>示例

print (df)
   userID gender  adID  rating
0      11      m   107      50
1      11      m   108     100
2      11      m   109       0


s1 = df.copy()
s2 = df.copy()

s1['userID'] = df['userID'] + 5
s1['adID'] = df['adID'] + 3
s2['userID'] = s1['userID'] + 5
s2['adID'] = df['adID'] + 4

r1=df.append(s1)
r2=r1.append(s2)

print(r2)
   userID gender  adID  rating
0      11      m   107      50
1      11      m   108     100
2      11      m   109       0
0      16      m   110      50
1      16      m   111     100
2      16      m   112       0
0      21      m   111      50
1      21      m   112     100
2      21      m   113       0