【问题标题】:How would I get the value of first or second column in csv file given the value of last column using python给定使用python的最后一列的值,我将如何获取csv文件中第一列或第二列的值
【发布时间】:2021-10-23 07:21:10
【问题描述】:

我正在构建汽车生日愿望项目。到目前为止,我已经设法遍历月份和日期并检查日期时间,但如果日期和月份匹配,我需要获取第一列的值,以便函数可以转发电子邮件。

with open("birthdays.csv") as birthday_file:
    birthday = pd.read_csv(birthday_file)
    month_data = birthday.month
    date_data = birthday.day
    birthday_month = [month for month in month_data]
    birthday_date = [day for day in date_data]

csv 文件包含以下信息

name, email, year, month, day
Test, test@email.com,1961,12,21
Charlotte, me@yahoo.com, 2021,08,22

【问题讨论】:

  • 欢迎来到 Stack Overflow!请拨打tour。你说的是最后一栏还是最后两栏?请给出一个完整的例子,包括输入值和预期输出。你可以edit。如果您想了解更多提示,请查看How to Ask
  • 题外话,但你不需要 with 块中的所有东西。只需要第一行,因为它是唯一使用birthday_file 的部分。
  • 顺便说一句,我必须在这里添加skipinitialspace=Truepd.read_csv(birthday_file, skipinitialspace=True)
  • 您好,感谢您的回复。新手,所以学习如何使用它。如果我将同一行的最后两列的值与 datetime 函数匹配,那么我将如何获得同一行的第一列和第二列的值。示例输出 Charlotte & me@yahoo.com,匹配值 22 和 08

标签: python pandas


【解决方案1】:

举个例子,试试这样:

import pandas as pd

# open the file to a dataframe called 'df'
# df = pd.read_csv('yourFile.csv')

# for this demo use:
df = pd.DataFrame({'name': {0: 'Test', 1: 'Charlotte'},
 ' email': {0: 'test@email.com', 1: 'me@yahoo.com'},
 ' year': {0: 1961, 1: 2020},
 ' month': {0: 12, 1: 8},
 ' day': {0: 21, 1: 25}})

# remove spaces in the column names
df.columns = df.columns.str.replace(' ', '')

# get the individual columns that make up the date to a column with a datetime format
df = df.astype({'year': 'str', 'month': 'str', 'day': 'str'})
df['date'] = df[['year', 'month', 'day']].agg('-'.join, axis=1)
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
del df['month'], df['year']

print(df)

'''
    >>         name           email day         date
    >> 0       Test  test@email.com  21   1961-12-21
    >> 1  Charlotte    me@yahoo.com  25   2020-08-25
'''

# create a function to return all email addresses (as a list)
# where the month matches the current month and the day is one week in the future
def sendReminders(delay=7):
    
    return (df.loc[(df['date'].dt.dayofyear > pd.Timestamp.now().dayofyear) &
                    (df['date'].dt.dayofyear <= (pd.Timestamp.now().dayofyear + delay)), 'email'].tolist())
    
# call the function to return a list of emails for reminders but override the 7 days and set to 5 day as an example
print(sendReminders(5))

'''
    >> ['me@yahoo.com']
'''

print('\n')

显然,您会继续添加更多功能等。重点是清理数据并以正确的格式获取正确的列。 组织好数据框中的数据后,您可以进行各种计算。很有可能已经有方法了,你只需要找到它。

【讨论】:

    猜你喜欢
    • 2014-09-06
    • 1970-01-01
    • 2018-09-14
    • 2014-10-04
    • 2014-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多