在向datafram分配数据时,如何发生以下情况

2024-09-30 22:12:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我的理解是,在“=”操作数的情况下,信息从右向左流动。i、 e.a=b意味着b的值被转移到a。如果我后来改变了a,它不应该影响b的值。但在下面的代码中,它正在发生。有人能告诉我为什么会这样吗

df_main=fivminohlc

result=df_main.dtypes

print(result)

result=fivminohlc.dtypes

print(result)

O    float64
H    float64
L    float64
C    float64
V      int64
dtype: object
O    float64
H    float64
L    float64
C    float64
V      int64
dtype: object

df_main['Y1']=(df_main['C']-df_main['O'])/df_main['O'] # I have not touched fivminohlc

df_main['Y'] = np.where((df_main.Y1 > .001), 2, 1) 

df_main['Y'] = np.where((df_main.Y1 < -.001), 0, 1) 

result=df_main.dtypes

print(result)

result=fivminohlc.dtypes

print(result)

O     float64
H     float64
L     float64
C     float64
V       int64
Y1    float64
Y       int32
dtype: object
O     float64
H     float64
L     float64
C     float64
V       int64
Y1    float64
Y       int32
dtype: object

为什么Y和Y1在fivminohlc中显示


Tags: dfobjectmainnp情况resultwhereprint
1条回答
网友
1楼 · 发布于 2024-09-30 22:12:06

因为fivminohlc是一个类的实例,所以当您将它赋给dfèu main时,dfèu main实际上变成了指向fivminohlc的“指针”

dfèu main和fivminohlc都代表同一个实例。因此,通过更新dfu-main,您也在更新fivminohlc

class A:
    num = 1

a = A()
b = a
b.num = 2
print(a.num)
print(a == b)

将打印上述代码

2
True

请参阅以下文档:https://docs.python.org/3/tutorial/classes.html

第9.3.5节。类和实例变量也可能有用

复印

文档:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.copy.html

from pandas import DataFrame

# Instantiate an initial dataframe with columns "Name" and "RoomNumber"
df = DataFrame(columns=["Name", "RoomNumber"])

# Instantiate second_instance which effectively acts as a pointer to df's instance. 
# Also instantiate df_copy using df.copy() which copies the entirety of df into a
# new object.
second_instance = df
df_copy = df.copy()

# Update second_instance to add a new column, and print df. We can clearly see 
# that the change to second_instance affected df.
second_instance["NumberOfGuests"] = {}
print(df.columns)

# Now print df_copy. We can see that the above change to second_instance did not 
# affect df_copy as it is a separate instance.
print(df_copy.columns)

这将打印:

Index(['Name', 'RoomNumber', 'NumberOfGuests'], dtype='object')
Index(['Name', 'RoomNumber'], dtype='object')

相关问题 更多 >