我有一個像
data = {'ID': ['first_value', 'second_value', 'third_value',
'fourth_value', 'fifth_value', 'sixth_value'],
'list_id': [['001', 'ab0', '44A'], [], ['005', '006'],
['a22'], ['azz'], ['aaa', 'abd']]
}
df = pd.DataFrame(data)
我想創建兩列:
- 計算“list_id”上以“a”開頭的元素數量的列
- 計算“list_id”上不以“a”開頭的元素數量的列
我正在考慮做類似的事情:
data['list_id'].apply(lambda x: for entity in x if x.startswith("a")
我想先數以“a”開頭的那些,然后再數那些不以“a”開頭的,所以我這樣做了:
sum(1 for w in data["list_id"] if w.startswith('a'))
此外,這并沒有真正起作用,我無法使它起作用。
有任何想法嗎?:)
uj5u.com熱心網友回復:
假設這個輸入:
ID list_id
0 first_value [001, ab0, 44A]
1 second_value []
2 third_value [005, 006]
3 fourth_value [a22]
4 fifth_value [azz]
5 sixth_value [aaa, abd]
您可以使用:
sum(1 for l in data['list_id'] for x in l if x.startswith('a'))
輸出:5
如果您希望每行計數:
df['starts_with_a'] = [sum(x.startswith('a') for x in l) for l in df['list_id']]
df['starts_with_other'] = df['list_id'].str.len()-df['starts_with_a']
注意。使用串列推導比apply
輸出:
ID list_id starts_with_a starts_with_other
0 first_value [001, ab0, 44A] 1 2
1 second_value [] 0 0
2 third_value [005, 006] 0 2
3 fourth_value [a22] 1 0
4 fifth_value [azz] 1 0
5 sixth_value [aaa, abd] 2 0
uj5u.com熱心網友回復:
使用與您的建議非常相似的 pandas 的作業:
data = {'ID': ['first_value', 'second_value', 'third_value', 'fourth_value', 'fifth_value', 'sixth_value'],
'list_id': [['001', 'ab0', '44A'], [], ['005', '006'], ['a22'], ['azz'], ['aaa', 'abd']]
}
df = pd.DataFrame(data)
df["len"] = df.list_id.apply(len)
df["num_a"] = df.list_id.apply(lambda s: sum(map(lambda x: x[0] == "a", s)))
df["num_not_a"] = df["len"] - df["num_a"]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/469287.html
上一篇:從字串串列創建字典
下一篇:如何從多個字典創建資料框
