![](/img/trans.png)
[英]How to add the result of a divide function as a new column to the dataframe in Python?
[英]How to add a new column in the dataframe respecting a python rule?
我有以下 dataframe:
import numpy as np
import pandas as pd
df = pd.DataFrame({'Name': ['Station', 'Station', 'Sensor', 'Sensor',
'Sensor', 'Sensor', 'Station', 'Station'],
'id': [10, 10, 11, 11, 12, 12, 13, 13]})
print(df)
Output:
Name id
Station 10
Station 10
Sensor 11
Sensor 11
Sensor 12
Sensor 12
Station 13
Station 13
除了这个 dataframe 之外,我还有一个带有一些 id 的数组:
array_id = np.array([10, 11])
我想在 dataframe 中创建一个新列,称为 class,并分配标签“class1”和“class2”。 对于属于“array_id”的 id,它将收到“class1”,对于不属于“array_id”的 id,它将收到“class2”。 我尝试按照以下代码执行此操作:
# Create a new column with NaN
df['class'] = np.NaN
for i in range(0, len(df)):
for j in range(0, len(array_id)):
if(array_id[j] == df['id'].iloc[i]):
df['class'].iloc[i] = 'class1'
else:
df['class'].iloc[i] = 'class2'
(错误的)output 是:
print(df)
Name id class
Station 10 NaN
Station 10 NaN
Sensor 11 NaN
Sensor 11 NaN
Sensor 12 NaN
Sensor 12 NaN
Station 13 NaN
Station 13 NaN
我希望 output 是:
Name id class
Station 10 class1
Station 10 class1
Sensor 11 class1
Sensor 11 class1
Sensor 12 class2
Sensor 12 class2
Station 13 class2
Station 13 class2
如果你只想使用pandas
而没有numpy
,你可以使用loc
和fillna
:
df.loc[df.id.isin(array_id),'class'] = 'class1'
df['class'].fillna('class2',inplace=True)
Name id class
0 Station 10 class1
1 Station 10 class1
2 Sensor 11 class1
3 Sensor 11 class1
4 Sensor 12 class2
5 Sensor 12 class2
6 Station 13 class2
7 Station 13 class2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.