gpt4 book ai didi

python - 如何从 csv 数据添加数据框列

转载 作者:太空宇宙 更新时间:2023-11-03 15:55:53 25 4
gpt4 key购买 nike

我有 csv 数据

index   username
1 ailee
2 yura
3 sony
4 lily
5 alex
6 eunji
7 hyun
8 jingo
9 kim
10 min

集群的数据帧结果:

index   cluster
1 1
3 1
5 1
7 1
8 1
9 2
4 2
2 2
10 2
6 2

是否可以根据 csv 数据在 pd.dataframe 中添加用户名列?

最佳答案

我为此使用“DataFrame.merge”。这是代码

>>> import StringIO as sio
>>> import pandas as pd

>>> s1='''index username
1 ailee
2 yura
3 sony
4 lily
5 alex
6 eunji
7 hyun
8 jingo
9 kim
10 min'''
>>> s2 = '''index cluster
1 1
3 1
5 1
7 1
8 1
9 2
4 2
2 2
10 2
6 2'''

>>> df1=pd.read_csv(sio.StringIO(s1), index_col=0, delim_whitespace=True)
>>> df2=pd.read_csv(sio.StringIO(s2), index_col=0, delim_whitespace=True)

>>> df1
username
index
1 ailee
2 yura
3 sony
4 lily
5 alex
6 eunji
7 hyun
8 jingo
9 kim
10 min
>>> df2
cluster
index
1 1
3 1
5 1
7 1
8 1
9 2
4 2
2 2
10 2
6 2

>>> df1.merge(df2, left_index=True, right_index=True)
username cluster
index
1 ailee 1
3 sony 1
5 alex 1
7 hyun 1
8 jingo 1
9 kim 2
4 lily 2
2 yura 2
10 min 2
6 eunji 2

关于python - 如何从 csv 数据添加数据框列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40796263/

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