[英]How to classify values in a columns of a pandas data frame according to their value?
[英]Classify data by value in pandas
我有一個形式的pandas.DataFrame
low_bound high_bound name
0 10 'a'
10 20 'b'
20 30 'c'
30 40 'd'
40 50 'e'
我的pandas.Series
很長。 pandas.Series
形式:
value
5.7
30.4
21
35.1
我想給該Series的每個值對應於low_bound / high_bound / name DataFrame的對應名稱。 這是我的預期結果:
value name
5.7 'a'
30.4 'd'
21 'c'
35.1 'd'
確實,5.7名稱是'a',因為5.7介於0和10之間。
什么是最有效的代碼? 我知道我可以通過遍歷Series來解決問題,但是也許有一個更快的矢量解決方案正在使我逃脫。
最后請注意,我的范圍可以是自定義的,也可以是不規則的。 在此,出於示例的目的,它們是常規的。
熊貓有一種叫做cut
的方法,它將實現您想要的功能:
import pandas as pd
data = [{"low": 0, "high": 10, "name": "a"},
{"low": 10, "high": 20, "name": "b"},
{"low": 20, "high": 30, "name": "c"},
{"low": 30, "high": 40, "name": "d"},
{"low": 40, "high": 50, "name": "e"},]
myDF = pd.DataFrame(data)
#data to be binned
mySeries = pd.Series([5.7, 30.4, 21, 35.1])
#create bins from original data
bins = list(myDF["high"])
bins.insert(0,0)
print pd.cut(mySeries, bins, labels = myDF["name"])
這將為您提供以下內容,然后您可以將其放回某些數據框中,或者但是要保留數據:
0 a
1 d
2 c
3 d
dtype: category
Categories (5, object): [a < b < c < d < e]
根據垃圾箱的不規則程度(以及“自定義/不規則”的確切含義),您可能不得不求助於該系列的循環。 我想不出要為您處理此問題的內置組件,特別是考慮到它取決於垃圾箱中不規則的程度/類型。
明智地循環播放,如果您有一個上下限,則不管“規則性”如何,此方法都將起作用:
for el in mySeries:
print myDF["name"][(myDF["low"] < el) & (myDF["high"] > el)]
我很欣賞您可能不想遍歷龐大的序列,但是至少我們沒有手動索引到數據幀中,這可能會使事情變得更慢
你可以這樣做
buckets = [0, 10, 20, 30, 40]
buckets_name = ['a', 'b', 'c', 'd']
pd.cut(your_series, buckets , labels = buckets_name)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.