简体   繁体   English

熊猫Python新列数据框

[英]Pandas Python new column dataframe

I have problems with initializing a new column in a dataframe, called df I want to do: 我在初始化数据帧中要创建的名为df的新列时遇到问题:

df['new_column'] = 0

to have all values to zero.. 将所有值都设为零

But then is gives me: 但是那给了我:

A value is trying to be set on a copy of a slice from a DataFrame. 试图在DataFrame的切片副本上设置一个值。 Try using .loc[row_indexer,col_indexer] = value instead 尝试改用.loc[row_indexer,col_indexer] = value

.. so, when I then want to work on it it **** up... ..所以,当我接下来想要对其进行处理时,它会...

I looked up on the net but didn't really find something useful.. I am a beginner in pandas so sorry if the answer is obvious but I really don't know how to do this basic thing.. 我在网上查了一下,但并没有真正找到有用的东西。我是熊猫的初学者,所以很抱歉,如果答案很明显,但我真的不知道该怎么做。

Thanks! 谢谢!

I'm guessing this is because your df is already a view on some other dataframe like: 我猜这是因为您的df已经是其他一些数据框上的视图,例如:

df = DF.iloc[100:]

in this case pandas will not really copy the data but just keep a reference to the old one. 在这种情况下,熊猫不会真正复制数据,而只是保留对旧数据的引用。 In my mind this is not very transparent and I have shot myself in the foot a couple of times with that. 在我看来,这不是很透明,因此我已经把自己打了几下。

a work around is to enfoce a copy of the dataframe to be sure it owns its own data: 一种解决方法是提供数据框的副本,以确保它拥有自己的数据:

df = df.copy()

so in your case you might want to do: 因此,您可能需要执行以下操作:

df = df.copy()
df['new_column'] = 0

I hope that does the trick for you 我希望这可以帮到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM