我想将索引= [1,3,5,7,9]的数据帧的值更改为其他值。但是以下代码根本无法工作。
df = pd.DataFrame({'col1': [1000]*12})
s1 = pd.Series([i for i in range(2,7)])#supposedly new values
index = [2*i+1 for i in range(5)]#Given indices
df.iloc[index]['col1'] = s1#attempt to modify the values
print(df)
输出如下:
col1
0 1000
1 1000
2 1000
3 1000
4 1000
5 1000
6 1000
7 1000
8 1000
9 1000
10 1000
11 1000
C:/Users/User/Desktop/all python file/3.2.4/iloc_assign.py:13: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
答案 0 :(得分:1)
我相信您只需要
>>> df.loc[index, 'col1'] = s1.values
>>> df
col1
0 1000
1 2
2 1000
3 3
4 1000
5 4
6 1000
7 5
8 1000
9 6
10 1000
11 1000
答案 1 :(得分:1)
您还需要提供index
中的col1
,因为df.iloc
带有整数索引:
>>> df.iloc[index, 0] = s1.values
>>> df
col1
0 1000.0
1 2.0
2 1000.0
3 3.0
4 1000.0
5 4.0
6 1000.0
7 5.0
8 1000.0
9 6.0
10 1000.0
11 1000.0
您可以使用df.columns.get_loc
获取列的索引。因此,总体而言,您的代码应如下所示:
import pandas as pd
df = pd.DataFrame({'col1': [1000]*12})
s1 = pd.Series([i for i in range(2,7)])
index = [2*i+1 for i in range(5)]
df.iloc[index, df.columns.get_loc('col1')] = s1.values