[英]How can I read 2 columns in dataframe in pandas and return a list of lists of the data?
I just started learning pandas and I have a dataframe that looks like 我刚开始学习熊猫,我有一个看起来像
Date Average Volume
2013-02-07 400 4100
2013-02-08 389 3400
2013-02-23 380 3100
If the user says they want the information from the 1st column(I'm referring to the Average here, I am excluding date as its sort of a constant), I want it to return 如果用户说他们想要第一列中的信息(我在这里指的是平均值,则排除日期作为其常量),我希望它返回
['2013-02-07', 400]
['2013-02-08', 389]
['2013-02-23', 380]
If they asked for the info from the 2nd column it would return the date and volume info in the same format. 如果他们从第二列询问信息,它将以相同格式返回日期和数量信息。
data_list(file_object,column_number)
inp = int(input('Which column?' ))
if inp = 1:
df['Average'].iloc[0:]
if inp = 2:
df['Volume'].iloc[0:]
This returns the column the user wants, but how can I return it with the date in the format requested above? 这将返回用户想要的列,但是如何以上面要求的格式返回日期呢?
You can use values.tolist
您可以使用
values.tolist
>>> df[['Date','Average']].values.tolist()
[['2013-02-07', 400], ['2013-02-08', 389], ['2013-02-23', 380]]
If you want a generator, you can use map 如果需要发电机,可以使用地图
>>> map(list, df[['Date','Average']].values)
<map object at 0x7f3fd47023c8>
>>>
>>> [*map(list, df[['Date','Average']].values)]
[['2013-02-07', 400], ['2013-02-08', 389], ['2013-02-23', 380]]
You can precalculate your lists of lists and use a dictionary to store the results. 您可以预先计算列表列表,并使用字典来存储结果。 In addition, you can use
pd.Series.dt.strftime
to format your date as required. 此外,您可以根据需要使用
pd.Series.dt.strftime
设置日期格式。
Here's a demo: 这是一个演示:
df['Date'] = pd.to_datetime(df['Date'])
df_list = {col: df.assign(Date=df.Date.dt.strftime('%Y-%m-%d'))\
.loc[:, ['Date', col]].values.tolist() \
for col in ('Average', 'Volume')}
select = input('Enter a column name:\n')
print(df_list[select])
Example result: 结果示例:
Enter a column name:
Volume
[['2013-02-07', 4100], ['2013-02-08', 3400], ['2013-02-23', 3100]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.