如何根据 Pandas (python) 中的列表设置值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31128477/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:33:17  来源:igfitidea点击:

How to set values based on a list in Pandas (python)

pythonlistpandasdataframematching

提问by SteelyDanish

I have a maybe a hopefully easy question that I wasn't able to find an answer on stack.

我有一个可能很简单的问题,我无法在堆栈中找到答案。

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),如果“月”列中的值在列表 (some_list) 中,我想设置一个值 (some_value)。

e.g.

例如

df[df['month'].isin(some_list)] = some_value
df[df['month'].isin(some_list)] = some_value

It's barfing up an AttributeError: 'int' object has no attribute 'view'.

它引发了一个 AttributeError: 'int' object has no attribute 'view'。

Any helpful direction would be awesome.

任何有用的方向都会很棒。

[edit]:

[编辑]:

some_list = [4,5,6,7]
some_value = 100

df.month is a value from 1 - 12

df.month 是 1 - 12 之间的值

df.columns = ['datetime','weekday','hour','month','value']

df.columns = ['datetime','weekday','hour','month','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.

我意识到我还想找出 some_list 中的行的索引,然后使用这些索引将另一列的值('value')设置为 some_value。为最初没有写那个而道歉。

回答by Marius

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

...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.:

...表明您的问题更有可能是因为您混淆了变量的类型。目前我唯一能建议的就是只对特定列进行分配,因为您可能试图将 int 值分配给日期时间列或其他内容,例如:

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