无ID变量时如何合并两个DataFrame列生成单列长数据?
合并单列DataFrame为长列并生成占比条形图
1. 合并两个单列DataFrame
假设你的两个DataFrame分别为df1(列名Occupation1)和df2(列名Occupation2),可以用pandas.concat()实现纵向拼接,得到包含4000行的单列DataFrame:
import pandas as pd # 拼接两列并重置索引 combined_series = pd.concat([df1['Occupation1'], df2['Occupation2']], ignore_index=True) # 转换为指定列名的DataFrame result_df = pd.DataFrame({'Occupation': combined_series})
执行后result_df就是你需要的格式:
Occupation 0 Lobbyist 1 Government Employee 2 Government Employee 3 Lobbyist 4 Teacher 5 Teacher 6 Lawyer 7 Government Employee 8 Lobbyist 9 Teacher 10 Teacher
2. 计算职业占比
用value_counts()快速统计各职业的占比(转为百分比格式):
# 计算占比并保留两位小数 occupation_percent = result_df['Occupation'].value_counts(normalize=True).mul(100).round(2)
3. 绘制占比条形图
用matplotlib绘制直观的占比条形图:
import matplotlib.pyplot as plt # 设置图表大小和标题 plt.figure(figsize=(10, 6)) occupation_percent.plot(kind='bar') plt.title('职业占比分布') plt.xlabel('职业类型') plt.ylabel('占比 (%)') plt.xticks(rotation=45) # 旋转x轴标签避免重叠 plt.tight_layout() # 自动调整布局 plt.show()
内容的提问来源于stack exchange,提问作者user17073706
相关产品推荐
相关产品推荐

