Penal castration (gong 宮) was one of the five capital punishments (wuxing 五刑) in ancient China. It was the second heaviest penalty in ancient China, only second to the death penalty. It was applied to men (called geshi 割勢), and occasionally also to women (called youbi 幽閉, taking out the ovaries). An ancient word for it was zhuoxing 椓刑, a punishment allegedly used by the Miao tribes 苗 during the Xia period 夏 (21th - 17th cent. BCE).
The Qin 秦 (221-206 BCE) and Han 漢 (206 BCE-220 CE) dynasties used various words for it, like fuxing 腐刑, canshi xing 蠶室刑 or yinxing 陰刑. In oracle bone inscriptions, the term is written as a picture combining a knife and a penis. It was commonly applied to war captives from the Qiang 羌 tribes. About female castration, there are two theories. One explains the word youbi literally ("hidden enclosure"), meaning that women were put under a kind of house arrest (nüzi bi yu gong zhong 女子閉于宮中), Zheng Kangcheng's 鄭康成 commentary on the Zhouli 周禮), probably as a punishment for lasciviousness (yin 淫, in Baihutong 白虎通). Another interpretation sees it as a cruel extraction of the bowels, or suturing the openings.
Indecent behavior in any way was originally the crime to be punished with castration. Later on, rebellion was the main misdoing to apply this punishment. It was often combined with collective liability (lianzuo 連坐), and whole families were emasculated. It was widely used during the Qin period, because convicts were also used as state-owned slaves. When Emperor Wen 漢文帝 (r. 180-157 BCE) of the Han dynasty abolished mutilations (rouxing 肉刑) as punishment, he made an exemption with penal castration. In his reform of the penal law, Emperor Jing 漢景帝 (r. 157-141 BCE) allowed delinquents to choose between castration and execution. The most famous victim of this kind of penalty was Sima Qian 司馬遷, author of the history book Shiji 史記. Sima had defended general Li Ling 李陵, who had been accused of cowardice. The punishment was abolished by the Sui dynasty 隋 (581-618), and only rarely used thereafter, like by Emperor Muzong 遼穆宗 (r. 951-968) of the Liao dynasty 遼 (907-1125).