gpt4 book ai didi

python - 替换问题 - Pandas 数据框

转载 作者:太空宇宙 更新时间:2023-11-04 10:49:20 26 4
gpt4 key购买 nike

我有一个df

df:
date shares symbol date2
0 20120614 1100 AAT.N NaN
1 20120615 1100 AAT.N NaN
2 20120616 1100 AAT.N NaN
3 20120617 1100 AAT.N NaN
4 20030405 800 ABT.N NaN
5 20030406 800 ABT.N NaN
6 20030407 800 ABT.N NaN
...

#This is what I want:
df:
date shares symbol date2
0 20120614 1100 AAT.N 20120615
1 20120615 1100 AAT.N 20120616
2 20120616 1100 AAT.N 20120617
3 20120617 1100 AAT.N NaN
4 20030405 800 ABT.N 20030406
5 20030406 800 ABT.N 20030407
6 20030407 800 ABT.N NaN
...

我想将每个符号的 df.ix[0]['date2'] 替换为 df.ix[1]['date2'] - 符号通过数据帧发生变化,所以我不能只通过整个数据框。

我打算遍历,如果 i 和 i+1 的符号匹配:

df.ix[i]['symbol'] == df.ix[i+1]['symbol']

我打算用日期替换 NaN。

我试过:

df.ix[i]['date2'] = df.ix[i+1]['date']  ##This failed.

然后我尝试了:

a = df.ix[i+1]['date']
df.replace({'date2': i}, a)
###This failed as well

这里有什么建议

1) 完成此任务的最佳流程?

2) 基本问题:如何替换 pandas DF 中的 NaN(或什至另一个数字)?

谢谢。

最佳答案

这里有一个可能是最“泛泛”的单行解决方案:

In [8]: df['date2'] = df.groupby('symbol').apply(lambda x: x['date'].shift(-1))

In [9]: df
Out[9]:
date shares symbol date2
0 20120614 1100 AAT.N 20120615
1 20120615 1100 AAT.N 20120616
2 20120616 1100 AAT.N 20120617
3 20120617 1100 AAT.N NaN
4 20030405 800 ABT.N 20030406
5 20030406 800 ABT.N 20030407
6 20030407 800 ABT.N NaN

关于python - 替换问题 - Pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14961427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com