我需要根据Pandas数据帧中另一列的值设置一列的值.这是逻辑:
if df['c1'] == 'Value':
df['c2'] = 10
else:
df['c2'] = df['c3']
Run Code Online (Sandbox Code Playgroud)
我无法做到这一点,我只想创建一个具有新值的列(或更改现有列的值:任何一个适合我).
如果我尝试运行上面的代码或者如果我将其作为函数编写并使用apply方法,我会得到以下内容:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Run Code Online (Sandbox Code Playgroud) 我按照 DataCamp 课程的指南使用 XGBoost 分类。数据处理如下:
X, y = df.iloc[:,:-1], df.iloc[:,-1]
# Create a boolean mask for categorical columns: check if df.dtypes == object
categorical_mask = (X.dtypes == object)
# Get list of categorical column names
categorical_columns = X.columns[categorical_mask].tolist()
# Create LabelEncoder object: le
le = LabelEncoder()
# Apply LabelEncoder to categorical columns
X[categorical_columns] = X[categorical_columns].apply(lambda x: le.fit_transform(x))
# Create OneHotEncoder: ohe
ohe = OneHotEncoder(categorical_features=categorical_mask, sparse=False)
# Apply OneHotEncoder to categorical columns - output is no longer a dataframe: df_encoded is …Run Code Online (Sandbox Code Playgroud) 注意:我的问题标题有问题,所以如果你能想出更好的东西来帮助其他有类似问题的人,请告诉我,我会改变它.
存储为Pandas DataFrame
print(df)
week | site | vol
1 | a | 10
2 | a | 11
3 | a | 2
1 | b | 55
2 | b | 1
1 | c | 69
2 | c | 66
3 | c | 23
Run Code Online (Sandbox Code Playgroud)
请注意,站点b没有第3周的数据
week | site | vol
1 | a | 10
2 | a | 11
3 | a | 2
1 | b | 55
2 | …Run Code Online (Sandbox Code Playgroud) 我需要按列的子集进行分组,并计算其值的不同组合的数量。但是,还有其他列可能有也可能没有不同的值,我想以某种方式在输出中保留这些信息。这是一个例子:
gb1 gb2 text1 text2
bebop skeletor blue fisher
bebop skeletor blue wright
rocksteady beast_man orange haldane
rocksteady beast_man orange haldane
tokka kobra_khan green lande
tokka kobra_khan red arnold
Run Code Online (Sandbox Code Playgroud)
我只想gb1按和进行分组gb2。
这是我需要的:
gb1 gb2 count text1 text2
bebop skeletor 2 blue fisher, wright
rocksteady beast_man 2 orange haldane
tokka kobra_khan 2 green, red lande, arnold
Run Code Online (Sandbox Code Playgroud)
除了处理text1和text2列之外,我已经完成了所有工作。
提前致谢。