简体   繁体   English

我有 YEAR、MO、DY、HR 四个单独的列。 如何从 CSV 文件将其转换为 Python 中的一列

[英]I have four separate columns for YEAR, MO, DY, HR. How do I convert it into one column in Python from a CSV file

The CSV file is now like CSV 文件现在就像

YEAR MO DY DY HR人力资源
2011 2011 1 1 1 1 6 6

I want to be my python file to look like this:我想成为我的 python 文件,看起来像这样:

DATE/TIME:
2011-01-01 06:00:00

You can simply add columns to create one string and later convert it to datetime (and eventually drop old columns)您可以简单地添加列来创建一个字符串,然后将其转换为datetime时间(并最终删除旧列)

data = '''YEAR,MO,DY,HR
2011,1,1,6'''

import pandas as pd
import io

df = pd.read_csv(io.StringIO(data))
print(df)

df["Date/Time"] = df["YEAR"].astype(str) + "-" + df["MO"].astype(str) + "-" + df["DY"].astype(str) + " " + df["HR"].astype(str) + ":00:00"
df["Date/Time"] = pd.to_datetime(df["Date/Time"])
print(df)

df = df.drop(columns=['YEAR','MO','DY','HR'])
print(df)

Result:结果:

   YEAR  MO  DY  HR
0  2011   1   1   6

   YEAR  MO  DY  HR         Date/Time
0  2011   1   1   6  2011-01-01 06:00:00

            Date/Time
0 2011-01-01 06:00:00

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我有一个包含许多列和许多行的 CSV 文件。 如何从 Python 创建一列一 Excel 表? - I have a CSV file with many columns and many rows. How do I create a one column one Excel sheet from Python? 如何将带有一列的csv文件转换为Python中的字典? - How do I convert a csv file with one column to a dictionary in Python? 如何将一列中的数据放入单独的列中 - How do I put data from one column into separate columns 当我用csv编写代码时,如何在Python中分隔列 - When I write in csv how do I separate columns in Python 如何比较 csv 文件中一列的两行并在 Python 中相应地创建一个新列 - how do i compare two rows from one column in a csv file and create a new column accordingly in Python 我在 .csv 文件的特定列中有 MongoDB 格式的字符串行 如何将其转换为数据帧? - I have rows of strings in the MongoDB format in a specific column in the .csv file How do I convert it into dataframe? 如果我有一个CSV文件的Python列表,如何将它们全部合并为一个巨型CSV文件? - If I have a Python list of CSV files, how do I merge them all into one giant CSV file? Python:在DataFrame中,如何查找某一列中的字符串出现在另一列中的年份? - Python: In a DataFrame, how do I find the year that strings from one column appear in another column? PYTHON - 如何根据分隔符将一列分成两列 - PYTHON - How do I separate a column into two columns based on a delimiter 如何将列从一个 CSV 文件复制到另一个 CSV 文件? - How do I copy columns from one CSV file to another CSV file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM