在 pandas 中分配新列名和有条件地创建新列不起作用?

Assigning new column name and creating new column conditionally in pandas not working?

我有一个带有 pandas 的简单数据框,然后我将变量名称重命名为 'a' 和 'b'。

import pandas as pd
import numpy as np

df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})
df.columns = ['a', 'b']
print df
df['color'] = np.where(df['b']=='Z', 'green', 'red')
print df

   a  b
0  Z  A
1  Z  B
2  X  B
3  Y  C
   a  b color
0  Z  A   red
1  Z  B   red
2  X  B   red
3  Y  C   red

没有重命名行 df.columns,我得到

import pandas as pd
import numpy as np

df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})
#df.columns = ['a', 'b']
#print df
df['color'] = np.where(df['Set']=='Z', 'green', 'red')
print df

  Set Type  color
0   Z    A  green
1   Z    B  green
2   X    B    red
3   Y    C    red

我希望并期望第一组代码产生 "green green red red",但它失败了,我不知道为什么。

正如评论中所指出的,问题出在您如何重命名列。你最好重命名,像这样:

df = df.rename( columns={'Set': 'a','Type': 'b'})