Python 替换熊猫数据框中的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21723830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
replace rows in a pandas data frame
提问by Donbeo
I want to start with an empty data frame and then add to it one row each time.
I can even start with a 0 data frame data=pd.DataFrame(np.zeros(shape=(10,2)),column=["a","b"])and then replace one line each time.
我想从一个空的数据框开始,然后每次添加一行。我什至可以从 0 数据帧开始data=pd.DataFrame(np.zeros(shape=(10,2)),column=["a","b"]),然后每次替换一行。
How can I do that?
我怎样才能做到这一点?
回答by EdChum
Use .locfor label based selection, it is important you understand how to slice properly: http://pandas.pydata.org/pandas-docs/stable/indexing.html#selection-by-labeland understand why you should avoid chained assignment: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
使用.loc了基于标签的选择,重要的是你知道如何正确地切片:http://pandas.pydata.org/pandas-docs/stable/indexing.html#selection-by-label并了解为什么你应该避免链接分配:http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
In [14]:
data=pd.DataFrame(np.zeros(shape=(10,2)),columns=["a","b"])
data
Out[14]:
a b
0 0 0
1 0 0
2 0 0
3 0 0
4 0 0
5 0 0
6 0 0
7 0 0
8 0 0
9 0 0
[10 rows x 2 columns]
In [15]:
data.loc[2:2,'a':'b']=5,6
data
Out[15]:
a b
0 0 0
1 0 0
2 5 6
3 0 0
4 0 0
5 0 0
6 0 0
7 0 0
8 0 0
9 0 0
[10 rows x 2 columns]
回答by Greg Kendall
If you are replacing the entire row then you can just use an index and not need row,column slices. ...
如果要替换整行,则只需使用索引即可,不需要行、列切片。...
data.loc[2]=5,6
data.loc[2]=5,6

