나열 할 Pandas DataFrame 열
이 질문에는 이미 답변이 있습니다.
충족되는 다른 열의 조건에 따라 열에서 데이터 하위 집합을 가져옵니다.
올바른 값을 다시 얻을 수는 있지만 pandas.core.frame.DataFrame에 있습니다. 목록으로 변환하려면 어떻게합니까?
import pandas as pd
tst = pd.read_csv('C:\\SomeCSV.csv')
lookupValue = tst['SomeCol'] == "SomeValue"
ID = tst[lookupValue][['SomeCol']]
#How To convert ID to a list
사용 .values을 얻기 위해 numpy.array다음과 .tolist()목록을 얻을 수 있습니다.
예를 들면 다음과 같습니다.
import pandas as pd
df = pd.DataFrame({'a':[1,3,5,7,4,5,6,4,7,8,9],
'b':[3,5,6,2,4,6,7,8,7,8,9]})
결과:
>>> df['a'].values.tolist()
[1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9]
아니면 그냥 사용할 수 있습니다
>>> df['a'].tolist()
[1, 3, 5, 7, 4, 5, 6, 4, 7, 8, 9]
복제본을 삭제하려면 다음 중 하나를 수행하십시오.
>>> df['a'].drop_duplicates().values.tolist()
[1, 3, 5, 7, 4, 6, 8, 9]
>>> list(set(df['a'])) # as pointed out by EdChum
[1, 3, 4, 5, 6, 7, 8, 9]
몇 가지 사항을 명확히하고 싶습니다.
- 다른 답변에서 지적했듯이 가장 간단한 작업은 use
pandas.Series.tolist()입니다. 내가 알 수있는 한 왜 가장 많이 투표 된 답변이 사용으로 이어질 지 잘 모르겠습니다pandas.Series.values.tolist(). 추가 혜택없이 구문 / 혼란을 추가합니다. tst[lookupValue][['SomeCol']]는 데이터 질문 (질문에 언급 된)이 아닌 일련의 질문 (질문에 언급 된)입니다. 이것은tst[lookupValue]데이터 프레임 이기 때문에[['SomeCol']]열을 슬라이싱하면 열 목록 (길이가 1 인 열 목록)을 요청하여 데이터 프레임이 반환되기 때문입니다. 에서와 같이 추가 대괄호 세트를 제거하면tst[lookupValue]['SomeCol']열 목록이 아닌 하나의 열만 요청하므로 시리즈가 다시 나타납니다.- 를 사용하려면 시리즈가 필요
pandas.Series.tolist()하므로이 경우 두 번째 대괄호 세트를 건너 뛰어야합니다. 참고로, 이와 같이 쉽게 피할 수없는 1 열 데이터 프레임이 발생하면이pandas.DataFrame.squeeze()를 시리즈로 변환하는 데 사용할 수 있습니다 . tst[lookupValue]['SomeCol']체인 슬라이싱을 통해 특정 열의 하위 집합을 가져옵니다. 특정 행만 남은 데이터 프레임을 얻기 위해 한 번 슬라이스 한 다음 특정 열을 얻기 위해 다시 슬라이스합니다. 당신이 글을 쓰는 것이 아니라 단지 읽기 때문에 여기에서 벗어날 수 있지만, 그것을하는 올바른 방법은tst.loc[lookupValue, 'SomeCol'](시리즈를 반환합니다)입니다.- # 4의 구문을 사용하면 모든 것을 한 줄에 합리적으로 수행 할 수 있습니다.
ID = tst.loc[tst['SomeCol'] == 'SomeValue', 'SomeCol'].tolist()
데모 코드 :
import pandas as pd
df = pd.DataFrame({'colA':[1,2,1],
'colB':[4,5,6]})
filter_value = 1
print "df"
print df
print type(df)
rows_to_keep = df['colA'] == filter_value
print "\ndf['colA'] == filter_value"
print rows_to_keep
print type(rows_to_keep)
result = df[rows_to_keep]['colB']
print "\ndf[rows_to_keep]['colB']"
print result
print type(result)
result = df[rows_to_keep][['colB']]
print "\ndf[rows_to_keep][['colB']]"
print result
print type(result)
result = df[rows_to_keep][['colB']].squeeze()
print "\ndf[rows_to_keep][['colB']].squeeze()"
print result
print type(result)
result = df.loc[rows_to_keep, 'colB']
print "\ndf.loc[rows_to_keep, 'colB']"
print result
print type(result)
result = df.loc[df['colA'] == filter_value, 'colB']
print "\ndf.loc[df['colA'] == filter_value, 'colB']"
print result
print type(result)
ID = df.loc[rows_to_keep, 'colB'].tolist()
print "\ndf.loc[rows_to_keep, 'colB'].tolist()"
print ID
print type(ID)
ID = df.loc[df['colA'] == filter_value, 'colB'].tolist()
print "\ndf.loc[df['colA'] == filter_value, 'colB'].tolist()"
print ID
print type(ID)
결과:
df
colA colB
0 1 4
1 2 5
2 1 6
<class 'pandas.core.frame.DataFrame'>
df['colA'] == filter_value
0 True
1 False
2 True
Name: colA, dtype: bool
<class 'pandas.core.series.Series'>
df[rows_to_keep]['colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df[rows_to_keep][['colB']]
colB
0 4
2 6
<class 'pandas.core.frame.DataFrame'>
df[rows_to_keep][['colB']].squeeze()
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[rows_to_keep, 'colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[df['colA'] == filter_value, 'colB']
0 4
2 6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>
df.loc[rows_to_keep, 'colB'].tolist()
[4, 6]
<type 'list'>
df.loc[df['colA'] == filter_value, 'colB'].tolist()
[4, 6]
<type 'list'>
당신이 사용할 수있는 pandas.Series.tolist
예 :
import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})
운영:
>>> df['a'].tolist()
당신은 얻을 것이다
>>> [1, 2, 3]
The above solution is good if all the data is of same dtype. Numpy arrays are homogeneous containers. When you do df.values the output is an numpy array. So if the data has int and float in it then output will either have int or float and the columns will loose their original dtype. Consider df
a b
0 1 4
1 2 5
2 3 6
a float64
b int64
So if you want to keep original dtype, you can do something like
row_list = df.to_csv(None, header=False, index=False).split('\n')
this will return each row as a string.
['1.0,4', '2.0,5', '3.0,6', '']
Then split each row to get list of list. Each element after splitting is a unicode. We need to convert it required datatype.
def f(row_str):
row_list = row_str.split(',')
return [float(row_list[0]), int(row_list[1])]
df_list_of_list = map(f, row_list[:-1])
[[1.0, 4], [2.0, 5], [3.0, 6]]
참고URL : https://stackoverflow.com/questions/23748995/pandas-dataframe-column-to-list
'programing tip' 카테고리의 다른 글
| ArrayAdapter를 사용하는 방법 (0) | 2020.07.03 |
|---|---|
| 배열에서 첫 x 항목 반환 (0) | 2020.07.03 |
| JQuery없이 리스너에 여러 이벤트를 바인딩 하시겠습니까? (0) | 2020.07.03 |
| 길이가 긴 요청을 허용하도록 web.config를 구성하는 방법 (0) | 2020.07.03 |
| RVM 설치 중 "gpg : command not found"오류를 해결하는 방법? (0) | 2020.07.03 |