简体   繁体   English

根据条件将数据框的值移动到列表

[英]Move Values of a dataframe to a list based on a condition

I am trying to move the data from a single column in a dataframe to a list.我正在尝试将数据从数据框中的单列移动到列表中。

Account Name    Renewal % Change
Client 1        0%
Client 2        0%
Client 3        2%
Client 4        0%
Client 5        1%
Client 6        1%

So If a client has 0% It should get added to the list Cost0 and it it has 1% it should get added to Cost1.所以如果一个客户有 0% 它应该被添加到列表 Cost0 并且它有 1% 它应该被添加到 Cost1。

I tried using a pd.series.tolist() but it kept giving me an error.我尝试使用 pd.series.tolist() 但它一直给我一个错误。

if brl['Renewal % Change'] == '0%':
    a = pd.Series(brl['Account Name'])
    a.tolist()

ValueError: The truth value of a Series is ambiguous. ValueError:系列的真值不明确。 Use a.empty, a.bool(), a.item(), a.any() or a.all()使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

Please advise请指教

Try this试试这个

Cost0 = brl[blr['Renewal % Change']=='0%']['Account Name'].tolist()
Cost1 = brl[blr['Renewal % Change']=='1%']['Account Name'].tolist()

Update更新

Using .loc使用.loc

Cost0 = brl.loc[blr['Renewal % Change']=='0%','Account Name'].tolist()
Cost1 = brl.loc[blr['Renewal % Change']=='1%','Account Name'].tolist()

You can use a bit changed boolean indexing with selecting column by loc :您可以通过loc选择列来使用稍微改变的boolean indexing

mask = brl['Renewal % Change'] == '0%'
print (mask)
0     True
1     True
2    False
3     True
4    False
5    False
Name: Renewal % Change, dtype: bool

print (brl.loc[mask, 'Account Name'].tolist())
['Client 1', 'Client 2', 'Client 4']

All together:一起来:

Cost0 = brl.loc[brl['Renewal % Change'] == '0%', 'Account Name'].tolist()
print (Cost0)
['Client 1', 'Client 2', 'Client 4']

Cost1 = brl.loc[brl['Renewal % Change'] == '1%', 'Account Name'].tolist()
print (Cost1)
['Client 5', 'Client 6']

You get error, because comparing return boolean Series - array, not scalar value, see docs :你得到错误,因为比较返回布尔Series - 数组,而不是标量值,请参阅文档

print (brl['Renewal % Change'] == '0%')
0     True
1     True
2    False
3     True
4    False
5    False
Name: Renewal % Change, dtype: bool

Comparing solutions - with loc is faster:比较解决方案 - 使用loc更快:

In [137]: %timeit brl.loc[brl['Renewal % Change'] == '0%', 'Account Name'].tolist()
1000 loops, best of 3: 536 µs per loop

In [138]: %timeit brl[brl['Renewal % Change']=='0%']['Account Name'].tolist()
1000 loops, best of 3: 657 µs per loop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM