Python dataframe中的列具有列表作为值。如何创建此列的版本,但仅使用列表中的第一个值?
我目前的解决方案如下:Python dataframe中的列具有列表作为值。如何创建此列的版本,但仅使用列表中的第一个值?,python,pandas,series,Python,Pandas,Series,我目前的解决方案如下: prices_real = [] for item in sparkline['prices']: prices_real.append(item[0]) sparkline['prices_real'] = prices_real 但我想知道是否有一种更简单的方法或方法我不知道?您可以使用: 您的问题有两个方面: 提取序列中每个列表的第一个(也是唯一的)元素 将序列转换为数字 因此,您可以使用str访问器,后跟pd.\u num
prices_real = []
for item in sparkline['prices']:
prices_real.append(item[0])
sparkline['prices_real'] = prices_real
但我想知道是否有一种更简单的方法或方法我不知道?您可以使用:
您的问题有两个方面:
str
访问器,后跟pd.\u numeric
:
df = pd.DataFrame({'x': [['0.12312'], ['-5.32454'], ['0.563412'], ['-3.918324']]})
df['x'] = pd.to_numeric(df['x'].str[0])
print(df, df.dtypes, sep='\n'*2)
x
0 0.123120
1 -5.324540
2 0.563412
3 -3.918324
x float64
dtype: object
完美答案,除了一个小细节:PEP8指南不使用小写字母“l”作为变量名,因为它看起来太像数字1这会产生一个
对象
数据类型系列。不推荐。@G.Anderson:是的,我同意。但是我没能想出一个好名字,我只是用x
作为列名。在将其更改为OP在其数据帧中的内容后,我可以使用它:)@jpp:True,将其转换为与您的答案类似的数字会更好(但不是OP明确要求的)。@Graipher,Yeh,IMO如果您选择lambda
路线,您可能会从operator import itemgetter中选择。
df = pd.DataFrame({'x': [['0.12312'], ['-5.32454'], ['0.563412'], ['-3.918324']]})
df['x'] = pd.to_numeric(df['x'].str[0])
print(df, df.dtypes, sep='\n'*2)
x
0 0.123120
1 -5.324540
2 0.563412
3 -3.918324
x float64
dtype: object