【问题标题】:How do I search for a matching string in a datafram using pandas?如何使用 pandas 在数据框中搜索匹配的字符串?
【发布时间】:2020-10-31 13:58:42
【问题描述】:

我是一名初学者,在 Python 中使用 pandas 库。我目前有一个代码可以读取从我的桌面提取的 csv 文件,具体取决于我提供的程序标题:

string = input("Enter a ticker: ")
file = string + (".csv")
file_location = 'M:\\A*************\\r*******\\files\\r************.tar\\tmp\\p*********\\' + file

if config.is_file():
    print(file)
    print(file_location)
    df = pd.read_csv(file_location)
    #print(df)
else:
    print("Invalid ticker input")

这允许我的用户输入文件名,并使用 Pandas 读取文件。数据框有 2 列(时间戳、users_holding)和大约 17k 行。

我希望我的用户能够输入日期:

date = input("Enter a date (YYYY-MM-DD): ")

并且程序将返回具有相应日期(时间戳)和用户(users_holding)的行。 例如/

enter ticker: TSLA
enter a date (YYYY-MM-DD): 2019-08-23
timestamp     users_holding
2019-08-23    15,097

如果有人知道该怎么做,请告诉我!

【问题讨论】:

  • 你不需要搜索字符串——你应该使用正确的 pandas.Timestamps

标签: python pandas numpy dataframe date


【解决方案1】:
output_df = df[df['timestamp'] == date][['timestamp', 'users_holding']]

【讨论】:

  • 不要使用链式索引。一口气搞定:df.loc[df['timestamp'] == date, ['timestamp', 'users_holding']]
  • ```空数据框列:[timestamp, users_holding] 索引:[]
【解决方案2】:

您的用户给定日期可以作为变量 dt 接收

#Import libraries and and convert user given date to datetime:
from datetime import datetime
dt1 = datetime.strptime("2019-08-23", "%Y-%m-%d")\

#Do similar conversion for your Date column in pandas DF
#Filter all the dates equal to your date
df[ df['date'] == dt1 ] ['timestamp', ' 'users_holding']

在旁注中。请不要使用诸如“时间戳”之类的列名,这可能会导致您的代码发生冲突。 请养成将这些列重命名为“user_time_stamp”等标准的习惯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2021-09-06
    • 1970-01-01
    相关资源
    最近更新 更多