![](/img/trans.png)
[英]Select CONSECUTIVE rows from a DataFrame based on values in a column in Pandas with Groupby
[英]Pandas select rows from a DataFrame based on column values?
我已將以下json
字符串加載到dataframe
。 現在我想根據ossId
過濾記錄。
我的條件是給出錯誤信息。 按ossId過濾的正確方法是什么?
import pandas as pd
data = """
{
"components": [
{
"ossId": 3946,
"project": "OALX",
"licenses": [
{
"name": "BSD 3",
"status": "APPROVED"
}
]
},
{
"ossId": 3946,
"project": "OALX",
"version": "OALX.client.ALL",
"licenses": [
{
"name": "GNU Lesser General Public License v2.1 or later",
"status": "APPROVED"
}
]
},
{
"ossId": 2550,
"project": "OALX",
"version": "OALX.webservice.ALL" ,
"licenses": [
{
"name": "MIT License",
"status": "APPROVED"
}
]
}
]
}
"""
df = pd.read_json(data)
print(df)
df1 = df[df["components"]["ossId"] == 2550]
我認為您的問題是由於 json 結構引起的。 您實際上是將一行加載到df
中,該行是字段component
的整個列表。
您應該將記錄列表傳遞給 dataframe。 就像是:
json_data = json.loads(data)
df = pd.DataFrame(json_data["components"])
filtered_data = df[df["ossId"] == 2550]
您需要將 go 放入單元格的數據中並獲取正確的密鑰:
df[df['components'].apply(lambda x: x.get('ossId')==2550)]
使用str
df[df.components.str['ossId']==2550]
Out[89]:
components
2 {'ossId': 2550, 'project': 'OALX', 'version': ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.