python - Python:无法过滤 CSV,ValueError:只能将大小为 1 的数组转换为 Python 标量
问题描述
我有一个这样的 CSV:
| path | artists | item | id |
| ------------------------------- | ------- | ---- | ------------------ |
| ../gifs/dwight\_harry\_0.gif | dh | 0 | wUIh5rHf5QCyhIk8Ay |
| ../gifs/dwight\_beatles\_0.gif | db | 0 | OqBPFGQkA2rmoouv4A |
| ../gifs/michael\_harry\_0.gif | mh | 0 | ITAra7ShPMXQecbFGZ |
| ../gifs/michael\_beatles\_0.gif | mb | 0 | ryKfGjpxOvDM38b3sk |
| ../gifs/michael\_beatles\_0.gif | mb | 1 | hgKfGjpxOdfM38b3sk |
我想先按项目过滤它,然后artists
一个一个地选择每个值。例如,对于item = 1
,我只会选择mb
。这是我尝试过的:
item = 0
i = str(item)
df = pd.read_csv("../data/urls.csv")
# Select Item
df = df.loc[df['item'] == i]
dh_id = df.loc[df['artists'] == 'dh']['id'].item()
db_id = df.loc[df['artists'] == 'db']['id'].item()
mh_id = df.loc[df['artists'] == 'mh']['id'].item()
mb_id = df.loc[df['artists'] == 'mb']['id'].item()
这给了我以下错误:
File "D:\write_pages.py", line 67, in writepage
dh_id = df.loc[df['artists'] == 'dh']['id'].item()
ValueError: can only convert an array of size 1 to a Python scalar
我究竟做错了什么?
解决方案
国际大学联盟:
尝试:
df=df.apply(lambda x:x.str.strip(),axis=1)
out=df.groupby('artists')['id'].agg(lambda x:x.value_counts().idxmax())
的输出out
:
artists
db OqBPFGQkA2rmoouv4A
dh wUIh5rHf5QCyhIk8Ay
mb hgKfGjpxOdfM38b3sk
mh ITAra7ShPMXQecbFGZ
Name: id, dtype: object
或者
删除“艺术家”的重复值:
out=df.sort_values('item',ascending=False).drop_duplicates('artists')
输出:
path artists item id
0 ../gifs/michael\_beatles\_0.gif mb 1 hgKfGjpxOdfM38b3sk
1 ../gifs/dwight\_harry\_0.gif dh 0 wUIh5rHf5QCyhIk8Ay
2 ../gifs/dwight\_beatles\_0.gif db 0 OqBPFGQkA2rmoouv4A
3 ../gifs/michael\_harry\_0.gif mh 0 ITAra7ShPMXQecbFGZ
注意:您收到此错误是因为df.loc[df['artists'] == 'mb']['id']
给您 2 个值并且根据文档Series.item
It will raise value error If the data is not length-1 and the value need to be scaler.
推荐阅读
- c# - 从集合中过滤数据
- reactjs - 如何在 React Native 中加密数据(使用 Expo)
- math - 为什么我没有将十进制精度提高到 1 位?
- java - Java SHA-256 程序提供了错误的哈希
- c++ - C++ 中 Vector 的 std::upper_bound 和 std::lower_bound 的复杂性是多少?
- javascript - 我的 d3 折线图中的画笔功能未按预期工作
- node.js - 如果 www 不在反应 js Web 应用程序中的 URL 中,则将 www 添加到安全 URL
- jquery - 选择第一个元素的多选
- node.js - 为什么带有redshift的nodejs pg总是只返回一行?
- javascript - 如何提高webgl中texSubImage2D的效率?