如何根据 Pandas (python) 中的列表设置值 [英] How to set values based on a list in Pandas (python)
问题描述
我有一个可能很简单的问题,就是我无法在堆栈上找到答案.
I have a maybe a hopefully easy question that I wasn't able to find an answer on stack.
我有一个数据框(df),并且如果列表中的月"列中的值在列表(some_list)中,我想设置一个值(some_value).
I have a a dataframe (df) and I want to set a value (some_value) if a value from the column 'month' is in a list (some_list).
例如
df[df['month'].isin(some_list)] = some_value
正在抛出AttributeError:'int'对象没有属性'view'.
It's barfing up an AttributeError: 'int' object has no attribute 'view'.
任何有用的指导都会很棒.
Any helpful direction would be awesome.
:
some_list = [4,5,6,7]
some_value = 100
df.month是1到12之间的值
df.month is a value from 1 - 12
df.columns = ['datetime','weekday','hour','month','value']
df.columns = ['datetime','weekday','hour','month','value']
我意识到我也想找出some_list中行的索引,然后使用这些索引将另一列的值(值")设置为some_value.很抱歉没有按原样写.
I realize I also want to find out the index of the rows which isin some_list then use those indices to set the value of another column ('value') to some_value. Apologies for not writing that originally.
推荐答案
您的问题似乎仍然没有足够的信息来找到真正的问题.这个简单的示例表明您的尝试可以正常进行:
Your question still doesn't seem to have enough information to find the real problem. This quick example shows that your attempt can work just fine:
import pandas as pd
df = pd.DataFrame({'x': [4, 5, 6], 'month': [1, 2, 3]})
some_list = [2, 3]
df[df['month'].isin(some_list)] = 99
df
Out[13]:
month x
0 1 4
1 99 99
2 99 99
...表明您的问题更有可能是因为您混淆了变量的类型.目前,我只能建议只对特定的列进行赋值,因为您可能试图将int值赋给datetime列或其他东西,例如:
...suggesting that your problem is more likely because you've mixed up the types of your variables. Currently the only thing I can suggest is only doing the assignment to specific columns, as you may be trying to assign an int value to a datetime column or something, e.g.:
df = pd.DataFrame({'x': [4, 5, 6], 'month': [1, 2, 3]})
some_list = [2, 3]
df.loc[df['month'].isin(some_list), 'x'] = 99
df
Out[14]:
month x
0 1 4
1 2 99
2 3 99
这篇关于如何根据 Pandas (python) 中的列表设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!