从列中获取前 2 个项目以创建另一个 Column Pandas
python 174
原文标题 :Get the first 2 items from a column to make another Column Pandas
我有一个带有 DateTime 列的表,如下所示。时间间隔以小时为单位
ID TimeInterval Temperature
1 00:00:00 27
2 01:00:00 26
3 02:00:00 24
4 03:00:00 24
5 04:00:00 25
我尝试使用时间间隔进行绘图。但是,我得到了一个错误float() argument must be a string or a number, not 'datetime.time'
所以,我想提取 Column TimeInterval 的前两个数字并将其放入一个新列中。任何想法如何提取它?
回复
我来回复-
Dieter 评论
如果“TimeInterval”列是一个字符串……您可以从中选择前 2 个字符,然后将其解析为一个整数:
df["new"] = df["TimeInterval"].str[:2].astype(int)
但这将是一个丑陋的解决方案。
这是一个更好的解决方案
# test data df = pd.DataFrame([{'TimeInterval':'00:00:00'}, {'TimeInterval':'01:00:00'}]) # cast it to a datetime object df['TimeInterval'] = pd.to_datetime(df['TimeInterval'], format='%H:%M:%S') # select the hours df['hours'] = df['TimeInterval'].dt.hour
2年前 -
Omar Ashraf 评论
你可以用
strftime
和%H
几个小时# Create test data df = pd.DataFrame({'ID': [1, 2, 3, 4, 5], 'TimeInterval': ['00:00:00', '01:00:00', '02:00:00', '03:00:00', '04:00:00'], 'Temperature': [27, 26, 24, 24, 25]}) # Change the format to %H:%M:%S. df['TimeInterval'] = pd.to_datetime(df['TimeInterval'], format='%H:%M:%S') # Create a new column df['new'] = df['TimeInterval'].dt.strftime('%H')
输出:
ID TimeInterval Temperature new 1 1900-01-01 00:00:00 27 00 2 1900-01-01 01:00:00 26 01 3 1900-01-01 02:00:00 24 02 4 1900-01-01 03:00:00 24 03 5 1900-01-01 04:00:00 25 04
2年前