Python 如何获得。假人和计数在同一时间
我有一个很大的数据集需要清理。现在,简化一下,我有:Python 如何获得。假人和计数在同一时间,python,count,pivot,Python,Count,Pivot,我有一个很大的数据集需要清理。现在,简化一下,我有: A B C D 1 1 5 2 2 4 2 5 3 1 5 3 3 2 1 8 4 1 4 4 因此,每列的值从1到5。 现在,我想将这4列转换为5个伪列,并同时计算每个值的每行的“值”数量,以便: S_1 S_2 S_3 S_4 S_5 1 1 2 0 0 1 4 1 1 1 0 1 5 1 1 2 0 0 8 1 0
A B C D
1 1 5 2 2
4 2 5 3 1
5 3 3 2 1
8 4 1 4 4
因此,每列的值从1到5。
现在,我想将这4列转换为5个伪列,并同时计算每个值的每行的“值”数量,以便:
S_1 S_2 S_3 S_4 S_5
1 1 2 0 0 1
4 1 1 1 0 1
5 1 1 2 0 0
8 1 0 0 3 0
所以“S_1”表示每行“1”的数量,“S_2”表示每行“2”的数量,依此类推
我想这在透视表中是可能的,但我做不到。有人能帮我吗?一种方法是使用:
输出
S_1 S_2 S_3 S_4 S_5
1 1 2 0 0 1
4 1 1 1 0 1
5 1 1 2 0 0
8 1 0 0 3 0
使用计数器计算出现次数,表达式为:
{**total, **Counter(row)}
为缺少的值创建一个计数为
0
的字典。您可以尝试一下,希望这有帮助
import pandas as pd
from collections import defaultdict # Initialize a dictionary with a default value
df = pd.DataFrame(
[[1,5,2,2],
[2,5,3,1],
[3,3,2,1],
[4,1,4,4]]
, columns = ['A','B','C','D'])
categories = [1,2,3,4,5]
# Count per row
rows_counts = []
for idx in df.index:
dict_counts = defaultdict(int)
# Count for each category
for category in categories:
# Get row as list to count()
row = df.loc[idx,:].tolist()
# Count
dict_counts[category] = row.count(category)
# Append results
rows_counts.append(dict_counts)
# Get desired output
new_df = pd.DataFrame(rows_counts)
new_df.columns = ['S_'+ str(cat) for cat in new_df.columns]
是的,成功了!但是,“0”是“Nan”。但是没有问题,因为我可以用0替换NAN。但是,第一列是“0”,然后以“S_1”、“S_2”等开头……你知道为什么第一列被命名为“0”吗?@bonaqua我用一个完整的示例更新了答案,用0和正确的索引填充了可能的nan。第一列是indexIn my dataset(稍微复杂一点),它仍然显示第一列为“0”,只有第二列是“S_1”,无法理解为什么。是这样的。数组([0',S_1',S_2',S_3',S_4',S_5',S_6',S_7',S_8',S_9',S_10',S_11',S_12',S_13',S_14',S_15',S_16',S_17',S_18',S_19',S_20',S_21']),dtype=object您如何定义总计,注意范围从1开始,两次都是从1开始的。我更新了答案,删除了第二个范围iterableCheck值的类型,它们可以是string,而不是int。
import pandas as pd
from collections import defaultdict # Initialize a dictionary with a default value
df = pd.DataFrame(
[[1,5,2,2],
[2,5,3,1],
[3,3,2,1],
[4,1,4,4]]
, columns = ['A','B','C','D'])
categories = [1,2,3,4,5]
# Count per row
rows_counts = []
for idx in df.index:
dict_counts = defaultdict(int)
# Count for each category
for category in categories:
# Get row as list to count()
row = df.loc[idx,:].tolist()
# Count
dict_counts[category] = row.count(category)
# Append results
rows_counts.append(dict_counts)
# Get desired output
new_df = pd.DataFrame(rows_counts)
new_df.columns = ['S_'+ str(cat) for cat in new_df.columns]