也许它看起来很奇怪,但您可以使用.str 从列表中获取元素
df.column1 = df.column1.str[-1]
有字典的时候也可以用
df.other = df.other.str[key]
最少的工作代码
import pandas as pd
df = pd.DataFrame({
'datetime.': [
'2021-04-10 00:03 00.',
'2021-04-10 00:06 00.',
'2021-04-10 00:09 00.'
],
'column1': [
[20.0, 21.6, 30.7],
[10.0, 20.6, 20.7],
[20.0, 21.5, 10.7]
],
'other': [
{'a': 20.0, 'b': 21.6, 'c': 30.7},
{'a': 10.0, 'b': 20.6, 'c': 20.7},
{'a': 20.0, 'b': 21.5, 'c': 10.7}
],
})
print(df)
df.column1 = df.column1.str[-1]
df.other = df.other.str['c']
print(df)
结果:
datetime. column1 other
0 2021-04-10 00:03 00. [20.0, 21.6, 30.7] {'a': 20.0, 'b': 21.6, 'c': 30.7}
1 2021-04-10 00:06 00. [10.0, 20.6, 20.7] {'a': 10.0, 'b': 20.6, 'c': 20.7}
2 2021-04-10 00:09 00. [20.0, 21.5, 10.7] {'a': 20.0, 'b': 21.5, 'c': 10.7}
datetime. column1 other
0 2021-04-10 00:03 00. 30.7 30.7
1 2021-04-10 00:06 00. 20.7 20.7
2 2021-04-10 00:09 00. 10.7 10.7
要同时对多个列执行相同操作,您还需要 .apply()
df[['column1', 'column2']] = df[['column1', 'column2']].apply(lambda column: column.str[-1]) # axis=0
或成行
df[['column1', 'column2']] = df[['column1', 'column2']].apply(lambda row: row.str[-1], axis=1)
顺便说一句:
如果您想将所有元素转换为列,则可以使用.apply(pd.Series)
df[ ["1", "2", "3"] ] = df.column1.apply(pd.Series)
df[ ["a", "b", "c"] ] = df.other.apply(pd.Series)