【问题标题】:How can following happen in assigning data to dataframe将数据分配给数据框时如何发生以下情况
【发布时间】:2019-11-13 15:32:35
【问题描述】:

我的理解是,在“=”操作数的情况下,信息从右向左流动。即 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

fivminohlc中怎么会显示Y和Y1

【问题讨论】:

  • 制作deep copy时,您仍在编辑原始元素。

标签: python dataframe math return-value assign


【解决方案1】:

因为 fivminohlc 是一个类的实例,所以当您将其分配给 df_main 时,df_main 本质上就变成了指向 fivminohlc 的“指针”。

df_main 和 fivminohlc 都代表同一个实例。因此,通过更新 df_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')

【讨论】:

  • 我认为 df_main 是我创建的一个新数据集。这是我理解中的一个根本性缺陷。万分感谢。但是,如何复制数据集而不遇到此类问题
  • 另外,为什么 fivminohlc 不是数据框而是一个类
  • @AIC 答案已更新。 DataFrame 是一个 Python 类。当您调用 DataFrame() 时,您会实例化此类的一个实例。 fivminohlc 是该类的一个实例(对象),但这并不意味着它不是一个数据框。请参阅此处的文档:pandas.pydata.org/pandas-docs/stable/reference/frame.html
  • 值得注意的是,Python 中的每个变量都是一个对象(类的一个实例)。见这里:jakevdp.github.io/WhirlwindTourOfPython/…
猜你喜欢
  • 1970-01-01
  • 2021-12-04
  • 1970-01-01
  • 2021-01-14
  • 1970-01-01
  • 2015-08-02
  • 2017-03-27
  • 1970-01-01
  • 2021-06-22
相关资源
最近更新 更多