Python 3.x 当属性有多个值时,列中属性的值计数
我试图根据国家列对netflix数据集进行计数和可视化,但在检查数据集时,我发现该列中有一些行包含多个国家值,例如 低于1; 下面是要计数的代码Python 3.x 当属性有多个值时,列中属性的值计数,python-3.x,pandas,count,Python 3.x,Pandas,Count,我试图根据国家列对netflix数据集进行计数和可视化,但在检查数据集时,我发现该列中有一些行包含多个国家值,例如 低于1; 下面是要计数的代码 country_count=joint_data['country'].value_counts().sort_values(ascending=False) country_count=pd.DataFrame(country_count) topcountries=country_count[0:11] topcountries.shape
country_count=joint_data['country'].value_counts().sort_values(ascending=False)
country_count=pd.DataFrame(country_count)
topcountries=country_count[0:11]
topcountries.shape
因此,我想将这些行作为单个国家进行计数,以获得正确的国家计数。您可以将
国家
列按,
拆分,然后按.explode()
拆分。下一步是.groupby()
:
印刷品:
country
Austria 1
Canada 1
Germany 1
India 2
United Kingdom 1
United States 1
dtype: int64
您可以从
'country'
列中编译所有可能的值,对其进行设置并为每个列创建新列
然后,您可以迭代您的行,并在该列位于该行内时进行填写“country”
:
import pandas as pd
df = pd.DataFrame({"country":["A,B,C","A,D,E,F","G"]})
print(df)
df[[*sorted(set(','.join(df["country"]).split(",")))]] = 0
for row in df.iterrows():
row[1][ [*(row[1]["country"].split(","))]] = 1
print(df)
输出:
country A B C D E F G
0 A,B,C 1 1 1 None None None None
1 A,D,E,F 1 None None 1 1 1 None
2 G None None None None None None 1
country A B C D E F G
0 A,B,C 1 1 1 0 0 0 0
1 A,D,E,F 1 0 0 1 1 1 0
2 G 0 0 0 0 0 0 1
A 2
B 1
C 1
D 1
E 1
F 1
G 1
如果您希望使用
0
而不是None
使用df.fillna(0,inplace=True)
转换它们:
# 0 instead of None
df.fillna(value=0, inplace=True)
print(df)
# print sums
for c in df.columns:
if c == "country":
continue
print(f"{c} {df[c].sum()}")
输出:
country A B C D E F G
0 A,B,C 1 1 1 None None None None
1 A,D,E,F 1 None None 1 1 1 None
2 G None None None None None None 1
country A B C D E F G
0 A,B,C 1 1 1 0 0 0 0
1 A,D,E,F 1 0 0 1 1 1 0
2 G 0 0 0 0 0 0 1
A 2
B 1
C 1
D 1
E 1
F 1
G 1