我认为这是一个错误,所以严格来说不是本网站的主题,但我希望这里的 pandas 社区能够提供帮助。让我们考虑这个数据框:
import pandas as pd
df = pd.DataFrame({'col1': [0,1,1,0,1], 'col2':list('aabbc')})
Run Code Online (Sandbox Code Playgroud)
如果我pd.get_dummies在第二列上使用前面有减号的内容,则我得到的结果如下:
print (-pd.get_dummies(df.col2))
a b c
0 255 0 0
1 255 0 0
2 0 255 0
3 0 255 0
4 0 0 255
Run Code Online (Sandbox Code Playgroud)
虽然可以使用以下方法获得预期结果str.get_dummies():
print (-df.col2.str.get_dummies())
a b c
0 -1 0 0
1 -1 0 0
2 0 -1 0
3 0 -1 0
4 0 0 -1
Run Code Online (Sandbox Code Playgroud)
我有python 3.7.1最新版本的 pandas 之一pd.__version__ == "0.24.2",在 Windows 10 上运行。
也许你想要
(-pd.get_dummies(df.col2, dtype=int))
Run Code Online (Sandbox Code Playgroud)
a b c
0 -1 0 0
1 -1 0 0
2 0 -1 0
3 0 -1 0
4 0 0 -1
Run Code Online (Sandbox Code Playgroud)
因为默认值dtype是pd.get_dummies8 位 unsigned int ( dtype : dtype, default np.uint8)?