Pandas 列的 To_CSV 唯一值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36107180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
To_CSV unique values of a pandas column
提问by ZJAY
When I use the following:
当我使用以下内容时:
import pandas as pd
data = pd.read_csv('C:/Users/Z/OneDrive/Python/Exploratory Data/Aramark/ARMK.csv')
x = data.iloc[:,2]
y = pd.unique(x)
y.to_csv('yah.csv')
I get the following error:
我收到以下错误:
AttributeError: 'numpy.ndarray' object has no attribute 'to_csv'
回答by Fabio Lamanna
IIUC, starting from a dataframe:
IIUC,从数据帧开始:
df = pd.DataFrame({'a':[1,2,3,4,5,6],'b':['a','a','b','c','c','b']})
you can get the unique values of a column with:
您可以通过以下方式获取列的唯一值:
g = df['b'].unique()
that returns an array:
返回一个数组:
array(['a', 'b', 'c'], dtype=object)
to save it into a .csv file I would transform it into a Series
s:
要将其保存到 .csv 文件中,我会将其转换为Series
s:
In [22]: s = pd.Series(g)
In [23]: s
Out[23]:
0 a
1 b
2 c
dtype: object
So you can easily save it:
所以你可以轻松地保存它:
In [24]: s.to_csv('file.csv')
Hope that helps.
希望有帮助。
回答by unutbu
The pandas equivalent of np.unique
is the drop_duplicates
method.
pandas 的等价物np.unique
是drop_duplicates
method。
In [42]: x = pd.Series([1,2,1,3,2])
In [43]: y = x.drop_duplicates()
In [46]: y
Out[46]:
0 1
1 2
3 3
dtype: int64
Notice that drop_duplicates
returns a Series, so you can call its to_csv
method:
请注意,它drop_duplicates
返回一个系列,因此您可以调用它的to_csv
方法:
import pandas as pd
data = pd.read_csv('C:/Users/Z/OneDrive/Python/Exploratory Data/Aramark/ARMK.csv')
x = data.iloc[:,2]
y = x.drop_duplicates()
y.to_csv('yah.csv')