[英]Taking a column from a csv file and putting it into a list in python
I need to write some code in python that takes a column from an csv file and makes it a list.我需要在 python 中编写一些代码,该代码从 csv 文件中获取一列并使其成为列表。 Here is my code until now.
到目前为止,这是我的代码。
import csv
from collections import defaultdict
columns = defaultdict(list)
with open('Team1_BoMInput.csv') as f:
reader = csv.DictReader(f)
for row in reader:
for (k,v) in row.items():
columns[k].append(v)
y = (columns['Quantity'])
x = (columns[('Actual Price')])
b = ['2', '2', '1', '1', '1', '1', '1', '1', '1', '2', '1', '1', '3', '4', '1', '1', '1', '8', '2', '2', '1', '1', '1', '1', '4', '1', '2', '2', '2', '1', '2', '2', '2', '1', '2', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '3', '2', '1', '1', '1']
a = ['$6.41', '$14.97', '$6.78', '$11.44', '$22.61', '$1.58', '$11.68', '$19.99', '$12.99', '$3.66', '$24.99', '$1.04', '$0.09', '$1.92', '$4.80', '$1.50', '$17.92', '$1.36', '$65.52', '$24.38', '$1.91', '$3.40', '$13.79', '$39.55', '$1.94', '$3.38', '$11.34', '$18.33', '$21.13', '$8.24', '$30.14', '$125.97', '$26.54', '$8.58', '$12.77', '$11.42', '$1.32', '$2.63', '$8.58', '$0.40', '$0.57', '$2.54', '$2.83', '$1.41', '$9.03', '$3.38', '$5.98', '$4.51', '$2.54', '$6.76', '$4.51', '$1.13', '$14.24']
for i in range(0, len(b)):
b[i] = float(b[i])
print(b)
x = ([s.strip('$') for s in a])
for i in range(0, len(x)):
x[i] = float(x[i])
print(x)
instead of having the values of a and b listed in the program, I want it to take the column from the csv file and use the values of that.而不是在程序中列出 a 和 b 的值,我希望它从 csv 文件中获取列并使用该值。 Thanks in advance
提前致谢
Try this:尝试这个:
import pandas as pd
df=pd.read_csv("Team1_BoMInput.csv")
y=list(df['Quantity'])
x=list(df['Actual Price'])
Refer the Below Code, leveraging the pandas
library for faster computations and lesser code请参考以下代码,利用
pandas
库进行更快的计算和更少的代码
import pandas as pd
df=pd.read_csv("Team1_BoMInput.csv")
quantity_list_value=list(df.loc[:,"Quantity"].astype(float).values)
price_list_value=list(df.loc[:,"Actual Price"].apply(lambda x: x.replace("$","")).astype(float).values)
I think you code will not run unless you change it to this:我认为除非您将其更改为以下代码,否则您的代码将不会运行:
import csv
from collections import defaultdict
columns = defaultdict(list)
with open('Team1_BoMInput.csv') as f:
reader = csv.DictReader(f)
for row in reader:
for (k,v) in row.items():
if k not in columns:
columns[k] = list()
columns[k].append(v)
# Rest of your code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.