[英]Select first few rows of pandas dataframe with a certain value in the column
我正在尝试根据另一列的值设置熊猫数据框中的一列值,
df2.loc[df2['col1',len] == val, 'col2'] = df1['col2']
上面的代码工作正常,但是,现在的问题是我只想为前几行设置值,如下所示:
len1 = len(df1.index)
df2.loc[df2['col1',len1] == val, 'col2'] = df1['col2']
但是我收到以下错误:
Traceback (most recent call last): File "...\\lib\\site-packages\\pandas\\indexes\\base.py", line 1945, in get_loc return self._engine.get_loc(key) File "pandas\\index.pyx", line 137, in pandas.index.IndexEngine.get_loc (pandas\\index.c:4154) File "pandas\\index.pyx", line 159, in pandas.index.IndexEngine.get_loc (pandas\\index.c:4018) File "pandas\\hashtable.pyx", line 675, in pandas.hashtable.PyObjectHashTable.get_item (pandas\\hashtable.c:12368)
任何帮助将不胜感激。
更改为此:
df2.iloc[:len(df1.index),].ix[df2.col1 == val, 'col2'] = df1['col2']
在这里,它不能确定到底出了什么问题。
name gender age occupation years_of_school married
0 Bob M 37 Dentist 20 N
1 Sally F 21 Student 16 N
2 Jim M 55 Carpenter 12 Y
3 Dan M 27 Teacher 18 Y
4 Rose F 14 Student 9 N
5 Emily F 65 Retired 22 Y
age_range
0 mid
1 young
2 old
3 young
4 young
这是一个示例查询:
df.iloc[:len(df1.index),].ix[df.age > 25, 'occupation'] = df1['age_range']
它返回的是:
name gender age occupation years_of_school married
0 Bob M 37 mid 20 N
1 Sally F 21 Student 16 N
2 Jim M 55 old 12 Y
3 Dan M 27 young 18 Y
4 Rose F 14 Student 9 N
5 Emily F 65 Retired 22 Y
我没有收到任何复制切片错误的信息。 那可能是由于您以前创建或处理DataFrame的方式造成的,但是我做到了这一点没有错误也没有问题。 除非我误解了您的原始问题,否则我不明白为什么要投反对票,甚至不知道为什么要投反对票,以便我可以解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.