python - 统计特定列中的重复项
问题描述
惠。我是一个新的 Python 用户。我需要编写一些脚本来从特定的 .txt 文件中提取数据。文件中的数据是:
Milo 12345678901234 DN127 POTATO_123_456
Milo 12345678901234 DN127 POTATO_123_456
Lamb 12345678901307 DN127 TOMATO_123_456
Lamb 12345678901618 DN127 TOMATO_123_456
Lamb 12345678901953 DN127 TOMATO_123_456
Milo 12345678902213 DN127 CHILI_789_0126
Milo 12345678902822 DN127 BANANA_134-123
脚本会做的是,它只会显示包含单词“Milo”的行,并计算第 4 列(第 3 列)中的重复项。我设法用“Milo”一词显示该行,但不知道如何计算第 8 列中的重复词。这是我到目前为止所做的:
with open ("food.txt") as food:
for line in food:
if line.find("\tMilo")!=-1:
print(line)
解决方案
使用熊猫:
df = pandas.read_csv('food.txt', sep = " ", header = None)
df.columns = ['Product', 'ID', 'Another ID', 'Some Code']
df = df[df['Product'].isin(['Milo'])]
df['Count of Repetitive Some Code'] = df.groupby('Some Code')['Some Code'].transform('count')
传奇:
Product
是你的专栏Milo, etc
ID
是你的专栏12345678901234, etc
Another ID
是你的专栏DN127, etc
Some Code
是您的列,POTATO_123_456, etc
==> 是您要计算的列。
推荐阅读
- python - 根据两个 pandas DataFrames 之间的条件为新列分配值
- xamarin.forms - Xamarin MSAL 何时调用 AcquireTokenSilent
- html - 有没有办法将 Coolmathgames.com 上的游戏嵌入到我的网站中?
- javascript - 在输入输入时更改 Div 的内容
- reactjs - 新的 React 项目 create-react-app 打开到 /public/index.html 而不是 App.js
- java - 时间戳检索方法
- c++ - 多次插入 (<<) 与连接输出 (+)
- python - python 3 jupyter notebook - 绘制蜡烛图
- javascript - 反应应用程序拒绝了 Firebase 权限
- swift - 将 NSObject 转换为可序列化的 JSON?