我有这个例子 pandas.DataFrame
有 +20K 行,格式如下:
import pandas as pd
import numpy as np
data = {"first_column": ["A", "B", "B", "B", "C", "A", "A", "A", "D", "B", "A", "A"],
"second_column": [0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0]}
df = pd.DataFrame(data)
>>> df
first_column second_column
0 A 0
1 B 1
2 B 1
3 B 1
4 C 0
5 A 0
6 A 0
7 A 1
8 D 1
9 B 1
10 A 1
11 A 0
....
first_column
列的每一行都有 A
、B
、C
和 D
。在第二列中,有一个二进制标签表示一组值。所有连续的 1 分组都是一个独特的“组”,例如第 1-3 行是一组,第 7-10 行是另一组。
我想通过“AB”(该组仅由 A 或 B 组成)、“CD”(该组仅由 C 或 D 组成)或“混合”(如果存在混合,例如所有 B 和一个 C)。了解这些分组中的一些“如何”与百分比混合也会很有用,即 AB 在总标签中的百分比。因此,如果它只是A
或B
,则标识应该是AB
。如果只是C
或D
,则标识应该是CD
。它是 A、B、C 和/或 D 的混合,然后是 mixed
。百分比是(AB 行数)/(总行数)
这是生成的 DataFrame
的样子:
>>> df
first_column second_column identity percent
0 A 0 0 0
1 B 1 AB 1.0
2 B 1 AB 1.0
3 B 1 AB 1.0
4 C 0 0 0
5 A 0 0 0
6 A 0 0 0
7 A 1 mixed 0.75 # 3/4, 3-AB, 4-total
8 D 1 mixed 0.75
9 B 1 mixed 0.75
10 A 1 mixed 0.75
11 A 0 0 0
....
我最初的想法是首先尝试将 df.loc()
与
if (df.first_column == "A" | df.first_column == "B"):
df.loc[df.second_column == 1, "identity"] = "AB"
if (df.first_column == "C" | df.first_column == "D"):
df.loc[df.second_column == 1, "identity"] = "CD"
但这并没有考虑到混合,也不适用于孤立的分组。
最佳答案
这是一种方法。
代码:
import pandas as pd
from collections import Counter
a_b = set('AB')
c_d = set('CD')
def get_id_percent(group):
present = Counter(group['first_column'])
present_set = set(present.keys())
if group['second_column'].iloc[0] == 0:
ret_val = 0, 0
elif present_set.issubset(a_b) and len(present_set) == 1:
ret_val = 'AB', 0
elif present_set.issubset(c_d) and len(present_set) == 1:
ret_val = 'CD', 0
else:
ret_val = 'mixed', \
float(present['A'] + present['B']) / len(group)
return pd.DataFrame(
[ret_val] * len(group), columns=['identity', 'percent'])
测试代码:
data = {"first_column": ["A", "B", "B", "B", "C", "A", "A",
"A", "D", "B", "A", "A"],
"second_column": [0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0]}
df = pd.DataFrame(data)
groupby = df.groupby((df.second_column != df.second_column.shift()).cumsum())
results = groupby.apply(get_id_percent).reset_index()
results = results.drop(['second_column', 'level_1'], axis=1)
df = pd.concat([df, results], axis=1)
print(df)
结果:
first_column second_column identity percent
0 A 0 0 0.00
1 B 1 AB 0.00
2 B 1 AB 0.00
3 B 1 AB 0.00
4 C 0 0 0.00
5 A 0 0 0.00
6 A 0 0 0.00
7 A 1 mixed 0.75
8 D 1 mixed 0.75
9 B 1 mixed 0.75
10 A 1 mixed 0.75
11 A 0 0 0.00
关于python - Pandas 数据框 : create new columns of labels based on other columns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43596242/