我的数据框有两列,一列包含单位,另一列具有值。
df4 = pd.DataFrame({'D': ['g', 'Kg', 'l', 'ml'],
'F': ['500', '1', '1', '1000']})
我正在尝试将Kg转换为g,将l转换为ml。我尝试过:
for row in final_df.iterrows():
if final_df['D']=='Kg':
final_df['F']=(final_df['F']*1000)
final_df['D']='g'
elif final_df['D']=='l':
final_df['F']=(final_df['F']*1000)
final_df['D']='ml'
预期输出:
D F
g 500
g 1000
ml 1000
ml 1000
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
答案 0 :(得分:0)
使用-
int levelNode(struct Node* root, int a)
{
node *temp = root;
int level = 0;
while (temp != NULL)
{
if (temp->data == a)
break;
level ++;
if (a > temp->data)
temp = temp->right;
else if (a < temp->data)
temp = temp->left;
}
if (temp == NULL)
return 0;
if (temp->data == a)
return level;
return 0;
}
输出
#include <stdio.h>
#include <queue>
#include <map>
int levelNode(struct Node* root, int a)
{
std::queue<Node*> stack;
std::map<Node*, int> xmap;
stack.push(root);
xmap[root] = 0;
while (!queue.empty())
{
Node* f = queue.front();
if(f == NULL) return;
queue.pop();
if(f->data == a) return xmap[f];
if(f->left){
queue.push(f->left);
xmap[f->left] = xmap[f]+1;
}
if(f->right){
queue.push(f->right);
xmap[f->right] = xmap[f]+1;
}
}
return 0;
}
答案 1 :(得分:0)
代码Dheeraj有几个问题。我会尽力一一解释。
代码如下:
final_df = pd.DataFrame({'D': ['g', 'Kg', 'l', 'ml'],'F': [500, 1, 1, 1000]})
for row in range(len(list(final_df.iterrows()))):
if final_df['D'][row]=='Kg' or final_df['D'][row]=='l':
final_df['F'][row]=final_df['F'][row]*1000
print(final_df)
结果:
D F
0 g 500
1 Kg 1000
2 l 1000
3 ml 1000
答案 2 :(得分:0)
除了Viveks使用np.where
的答案外,您还可以考虑使用df.mask
,这是一种专门用于更新条件为真的列的方法:
df4['F'] = pd.to_numeric(df4['F'])
df4['F'].mask(df4['D'].isin(['Kg', 'l']), df4['F'] * 1000, inplace=True)
# D F
#0 g 500
#1 Kg 1000
#2 l 1000
#3 ml 1000
答案 3 :(得分:0)
结合to_numeric
+ isin
+ replace
函数:
In [215]: df = pd.DataFrame({'D': ['g', 'Kg', 'l', 'ml'], 'F': ['500', '1', '1', '1000']})
In [216]: df.F = pd.to_numeric(df.F)
In [217]: df.loc[df.D.isin(['Kg','l']), 'F'] *= 1000
In [218]: df.D.replace(to_replace={'Kg': 'g', 'l': 'ml'}, inplace=True)
In [219]: df
Out[219]:
D F
0 g 500
1 g 1000
2 ml 1000
3 ml 1000
答案 4 :(得分:0)
您可以使用此:
df['F'] = np.where(df['D'].isin(['Kg','l']), df['F'].astype(int) * 1000, df['F'])
df['D'] = np.where(df['D']=='Kg', 'g', df['D'])
df['D'] = np.where(df['D']=='l', 'ml', df['D'])
输出:
D F
0 g 500
1 g 1000
2 ml 1000
3 ml 1000